linux下如何用C制作录音程序
请假各位大师:
linux下如何用C进行录音,录成.WAV格式,或者其他格式谢谢
------解决方案--------------------alsa官网上有资料,下面是个例程:
Linux下的录音编程(转摘)
/* 此文件中定义了下面所有形如SND_的变量*/
#include <sys/soundcard.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <stdlib.h>
int main()
{
/* id:读取音频文件描述符;fd:写入的文件描述符。i,j为临时变量*/
int id,fd,i,j;
/* 存储音频数据的缓冲区,可以调整*/
char testbuf[4096];
/* 打开声卡设备,失败则退出*/
if ( ( id = open ( "/dev/audio", O_RDWR ) ) < 0 ) {
fprintf (stderr, " Can't open sound device!\n");
exit ( -1 ) ;
}
/* 打开输出文件,失败则退出*/
if ( ( fd = open ("test.wav",O_RDWR))<0){
fprintf ( stderr, " Can't open output file!\n");
exit (-1 );
}
/* 设置适当的参数,使得声音设备工作正常*/
/* 详细情况请参考Linux关于声卡编程的文档*/
i=0;
ioctl (id,SNDCTL_DSP_RESET,(char *)&i) ;
ioctl (id,SNDCTL_DSP_SYNC,(char *)&i);
i=1;
ioctl (id,SNDCTL_DSP_NONBLOCK,(char *)&i);
i=8000;
ioctl (id,SNDCTL_DSP_SPEED,(char *)&i);
i=1;
ioctl (id,SNDCTL_DSP_CHANNELS,(char *)&i);
i=8;
ioctl (id,SNDCTL_DSP_SETFMT,(char *)&i);
i=3;
ioctl (id,SNDCTL_DSP_SETTRIGGER,(char *)&i);
i=3;
ioctl (id,SNDCTL_DSP_SETFRAGMENT,(char *)&i);
i=1;
ioctl (id,SNDCTL_DSP_PROFILE,(char *)&i);
/* 读取一定数量的音频数据,并将之写到输出文件中去*/
for ( j=0; j<100;){
i=read(id,testbuf,4096);
if(i>0){
write(fd,testbuf,i);
j++;
}
}
/* 关闭输入、输出文件*/
close(fd);
close(id);
exit(0);
}
------解决方案--------------------自己以前写的播放PCM数据的程序。
播放是往声卡些数据
录音类似的。只是从声卡读数据
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <linux/soundcard.h>
#define OPEN_DSP_FAILED 0x00000001 /*open dsp failed!*/
#define SAMPLERATE_STATUS 0x00000002 /*samplerate status failed*/
#define SET_SAMPLERATE_FAILED 0x00000003 /*set samplerate failed*/
#define CHANNELS_STATUS 0x00000004 /*Channels status failed*/
#define SET_CHANNELS_FAILED 0x00000005 /*set channels failed*/
#define FMT_STATUS 0x00000006 /*FMT status failed*/
#define SET_FMT_FAILED 0x00000007 /*set fmt failed*/
#define OPEN_FILE_FAILED 0x00000008 /*opem filed failed*/
int Audio_Play(char *pathname,int nSampleRate,int nChannels,int fmt)
{
int dsp_fd,mix_fd,status,arg;
dsp_fd = open("/dev/dsp" , O_RDWR); /*open dsp*/
if(dsp_fd < 0)
{
return OPEN_DSP_FAILED;
}
arg = nSampleRate;
status = ioctl(dsp_fd,SOUND_PCM_WRITE_RATE,&arg); /*set samplerate*/
if(status < 0)
{
close(dsp_fd);
return SAMPLERATE_STATUS;
}
if(arg != nSampleRate)
{
close(dsp_fd);
return SET_SAMPLERATE_FAILED;
}
arg = nChannels; /*set channels*/
status = ioctl(dsp_fd, SOUND_PCM_WRITE_CHANNELS, &arg);
if(status < 0)
{
close(dsp_fd);
return CHANNELS_STATUS;
}
if( arg != nChannels)
{
close(dsp_fd);
return SET_CHANNELS_FAILED;
}
arg = fmt; /*set bit fmt*/
status = ioctl(dsp_fd, SOUND_PCM_WRITE_BITS, &arg);
if(status < 0)
{
close(dsp_fd);
return FMT_STATUS;
}