三、Linux下实现录放音
注意驱动程序中的默认参数,应用程序可以通过ioctl()函数设置新的取值。

Open()函数:采用何种模式对声卡进行操作也必须在打开设备时指定,对于不支持全双工的声卡来说,应该使用只读或者只写的方式打开,只有那些支持全双工的声卡,才能以读写的方式打开,这还依赖于驱动程序的具体实现。open_mode有三种选择:O_RDONLY,O_WRONLY和O_RDWR,分别表示只读、只写和读写。OSS建议尽量使用只读或只写,只有在全双工的情况下(即录音和放音同时)才使用读写模式。Linux 允许应用程序多次打开或者关闭与声卡对应的设备文件,从而能够很方便地在放音状态和录音状态之间进行切换。
注意,用户始终要读/写一个完整的采样。例如一个16-bit的立体声模式下,每个采样有4个字节,所以应用程序每次必须读/写4的倍数个字节。
源码如下:
#include<unistd.h>
#include<fcntl.h>
#include<sys/types.h>
#include<sys/ioctl.h>
#include<stdlib.h>
#include<stdio.h>
#include<linux/soundcard.h>
#define LENGTH 3 // 存储秒数
#define RATE 44100 // 采样频率
#define SIZE 16 // 量化位数
#define CHANNELS 2 // 声道数目
/* 用于保存数字音频数据的内存缓冲区*/
unsigned charbuf[LENGTH*RATE*SIZE*CHANNELS/8];
int main()
{
intfd; // 声音设备的文件描述符
intarg; // 用于ioctl调用的参数
intstatus; // 系统调用的返回值
/*打开声音设备 */
fd= open("/dev/sound/dsp", O_RDONLY);
if(fd< 0)
{
perror("openof /dev/sound/dsp failed");
exit(1);
}
/*设置采样时的量化位数 */
arg= SIZE;
status= ioctl(fd, SOUND_PCM_WRITE_BITS, &arg);
if(status== -1)
perror("SOUND_PCM_WRITE_BITSioctl failed");
if(arg!= SIZE)
perror("unableto set sample size");
/*设置采样时的声道数目 */
arg= CHANNELS;
status= ioctl(fd, SNDCTL_DSP_STEREO, &arg);
if(status== -1)
perror("SNDCTL_DSP_STEREOioctl failed");
if(arg!= CHANNELS)
perror("unableto set number of channels");
/*设置采样时的采样频率 */
arg= RATE;
status= ioctl(fd, SNDCTL_DSP_SPEED, &arg);
if(status== -1)
perror("SNDCTL_DSP_SPEEDioctl failed");
if(arg!= RATE)
perror("unableto set rate");
printf("Saysomething:\n");
status= read(fd, buf, sizeof(buf)); //recording
if(status!= sizeof(buf))
perror("readwrong number of bytes");
printf("Yousaid:\n");
close(fd);
fd= open("/dev/sound/dsp", O_WRONLY);
if(fd< 0)
{
perror("openof /dev/sound/dsp failed");
exit(1);
}
/*设置采样时的量化位数 */
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 toset sample size");
/*设置采样时的声道数目 */
arg = CHANNELS;
status = ioctl(fd, SNDCTL_DSP_STEREO,&arg);
if(status == -1)
perror("SNDCTL_DSP_STEREO ioctl failed");
if(arg != CHANNELS)
perror("unable toset number of channels");
/* 设置采样时的采样频率 */
arg = RATE;
status = ioctl(fd,SNDCTL_DSP_SPEED, &arg);
if(status == -1)
perror("SNDCTL_DSP_SPEED ioctl failed");
if(arg != RATE)
perror("unable toset rate");
status= write(fd, buf, sizeof(buf)); //playing
if(status!= sizeof(buf))
perror("wrotewrong number of bytes");
close(fd);
return0;
}
程序中的注意点是open()函数的参数设置,之前采用参数O_RDWR,结果放音时总是出现错误,具体出错原因可能与驱动程序的设置有关。本设计中,正确的设置是当recording时,选择O_RDONLY,当playing时,选择O_WRONLY。
本文永久更新链接地址:http://www.linuxidc.com/Linux/2014-06/103570.htm
