使用/dev/dsp的wav文件播放器源码

来源:互联网 发布:ubuntu 14.04硬件要求 编辑:程序博客网 时间:2024/06/05 21:56

转载于:http://blog.csdn.net/dux003/article/details/5459423

 

#include
#include
#include
#include
#include

void usage(const char* self)
{
   printf("usage:/n");
    printf("/t%s[-c channels -r rate -s samplesize] wavfile/n",self);
};

int set_fmt(int fd, int channels, int rate, intsamplesize)
{
    int c =channels;
    if(ioctl(fd, SNDCTL_DSP_CHANNELS, &c) == -1)
       exit(1);

    if(ioctl(fd, SNDCTL_DSP_SPEED, &rate) == -1)
       exit(1);

    if(ioctl(fd, SNDCTL_DSP_SAMPLESIZE, &samplesize) ==-1)
       exit(1);

    return0;
}

int main(int argc, char **argv)
{
    int i =1;
    char*filename = NULL;
    int channels= 1;
    intsamplerate = 8000;
    intsamplesize = 16;

    intdsp;
    intfd;
    charbuf[1024];
    intlen;

    if(argc%2)
   {
       usage(argv[0]);
       exit(1);
   }

    while (i< argc)
   {
       if (argv[i][0] != '-')
       {
           filename = argv[i];
           i++;
       }
       else
       {
           if (i+1 < argc)
             switch(argv[i][1])
               {
                   case 'c':
                       channels = atoi(argv[i+1]);
                       i += 2;
                           break;

                   case 'r':
                       samplerate = atoi(argv[i+1]);
                       i += 2;
                       break;

                   case 's':
                       samplesize = atoi(argv[i+1]);
                       i += 2;
                       break;

                   default:
                       perror("bad option/n");
                       exit(1);
               }
           }
           else
           {
               perror("bad options/n");
               exit(1);
           }
       }
   }

    dsp =open("/dev/dsp", O_RDWR);
    if (dsp ==-1)
   {
       perror("can not open /dev/dsp/n");
       exit(1);
   }

    set_fmt(dsp,channels, samplerate, samplesize);

    fd =open(filename, O_RDWR);
    if (fd ==-1)
   {
       close(dsp);

       fprintf(stderr, "can not open file %s/n",filename);
       exit(1);
   }

    while ((len= read(fd, buf, 1024)) > 0)
   {
       write(dsp, buf, len);
   }

   close(fd);
   close(dsp);

    return0;

原创粉丝点击