这是一个在QT下做的一个音频采集类,只是做一个练习。。
sound::sound(QObject *parent) :
QObject(parent)
{
QMessageBox::about(NULL,"test","loving china!!");//这个可以随便写,就一QMessageBox只是用来观察每次是否修改了。
}
int sound::record()
{
int id,fd,i,j;
char buf[4*1024];
fd = open("/dev/dsp",O_RDONLY);//打开设备/dev/dsp
if(fd<0)
{
perror("Couldn't open the file /dev/audio:");
return -1;
}
id = open("test.wav",O_RDWR | O_CREAT,755);//打开用来记录的文件(存放音频文件)
if(id<0)
{
perror("Couldn't open the file test.wav:");
return -1;
}
/*************Set the ioctl********************/
i =0;
if(ioctl(fd,SNDCTL_DSP_RESET,(char *)&i)==-1)perror("reset error:");
if(ioctl(fd,SNDCTL_DSP_SYNC,(char *)&i)==-1)perror("sync error:");
i =1;
if(ioctl(fd,SNDCTL_DSP_NONBLOCK,(char *)&i)==-1)perror("nonblock error:");
i=RATE;
if(ioctl(fd,SNDCTL_DSP_SPEED,(char *)&i)==-1){perror("speed error:");return -1;}//设置8K的采样率,其中RATE已经宏定义为8K了;
i=1;
if(ioctl(fd,SNDCTL_DSP_CHANNELS,(char *)&i)==-1)perror("channel error:");
i=AFMT_S16_NE;
if(ioctl(fd,SNDCTL_DSP_SETFMT,(char *)&i)==-1){perror("setfmt error:");return -1;}//设置采样格式,之前设了AFMT_S16_LE结果电流声明显然
if(i!=AFMT_S16_NE){printf("the device is not suppor the AFMT_S16_NE");return -1;}
i=3;
if(ioctl(fd,SNDCTL_DSP_SETTRIGGER,(char *)&i)==-1)perror("settrigger error:");
i=3;
if(ioctl(fd,SNDCTL_DSP_SETFRAGMENT,(char *)&i)==-1)perror("setfragment error");
i=1;
if(ioctl(fd,SNDCTL_DSP_PROFILE,(char *)&i)==-1)perror("profile error");
/*****************TO Work*********************/
i=0;
for(j=0;j<8000;)//这里的数字没太大重要,别太小就行了,主要是用来控制录制的音频的长短的
{
/*录取音频到缓冲区*/
i=read(fd,buf,32);//这里的第三个参数,32是可以调节的,这个是我调过的数值,其实也没太大规定,重点是play那里的那个;
printf("In the %dth time it had get %d bytes\n",j,i);
if(i>0)
{
/*从缓冲区把音频写到文件里头*/
write(id,buf,i);
j++;
}
}
close(fd);
close(id);//最后记得关闭文件
return 0;
}