DSP

linux dsp 播放音频文件

2019-07-13 10:33发布

1 2 3 4 5 6 7 #include #include #include #include #include #include #include /* 下面的三个参数是跟具体文件相关 * cmd: file 音频文件 * [file pass.wav] =>> pass.wav: RIFF (little-endian) data, WAVE audio, Microsoft PCM, 16 bit, mono 44100 Hz *  1. 16位 *  2. mono为当声道=1, Stereo为立体声=2 *  3. 44100HZ为频率这个大家都知道,及一秒钟采集或者播放音频的bit数量。 */ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 #define RATE 44100 #define SIZE 16 #define CHANNELS 1  // 1表示单声道,2为立体声 /* ................ */ unsigned charbuff[RATE * SIZE * CHANNELS / 8]; //buff里面正好放一秒钟的音频,下面的计时还要用 int main() {     intfd;     intwavfd; //wav文件的描述符     intarg;        /* ..ioctl..... */     intstatus;   /* ........ */     /* ...... */     fd = open("/dev/dsp", O_WRONLY);     if(fd < 0) {         printf("open of /dev/dsp failed");         exit(1);     }     wavfd = open("pass.wav",O_RDONLY);     if(wavfd < 0) {         printf("open of wav failed");         exit(1);     }     /* 设置bit */     arg = SIZE;     status = ioctl(fd, SOUND_PCM_WRITE_BITS, &arg);     if(status == -1)          perror("SOUND_PCM_WRITE_BITS ioctl failed");     if(arg != SIZE)          perror("unable to set sample size");     /* 设置channels */     arg = CHANNELS;     status = ioctl(fd, SOUND_PCM_WRITE_CHANNELS, &arg);     if(status == -1)         perror("SOUND_PCM_WRITE_CHANNELS ioctl failed");     if(arg != CHANNELS)         perror("unable to set number of channels");     /* 设置rate */     arg = RATE;     status = ioctl(fd, SOUND_PCM_WRITE_RATE, &arg);     if(status == -1)         perror("SOUND_PCM_WRITE_WRITE ioctl failed");     /* 从wav文件中读buff大小的内容,然后写入/dev/dsp中,直到文件结束 */
  
/* Q:这里我试验时播放了两次,不知道啥情况,如果大家也遇到了请指教。*/     while((status = read(wavfd, buff, sizeof(buff))) > 0) {         printf("read size = %d ", status);         write(fd, buff,sizeof(buff));         /* 下面的代码用于在更改播放文件的参数时,播放掉缓冲区内的内容,可以用,更保险*/         status = ioctl(fd, SOUND_PCM_SYNC, 0);         if(status == -1)             perror("SOUND_PCM_SYNC ioctl failed");     } }