设为首页 加入收藏

TOP

Linux下声卡编程(录制音频文件)
2014-11-24 02:26:18 来源: 作者: 【 】 浏览:2
Tags:Linux 声卡 编程 录制 音频 文件

参考教材:<Linux编程技术详解>杜华编著


页码:P186

将音频文件写入声卡的设备文件中可以实现音频文件的播放。而使用read函数来读取声卡设备文件中的内容,则可以实现录音功能。下面的程序代码实现了在Linux系统下使用声卡设备的录音功能。


具体代码如下:

//p6.8.c声卡录音功能
#include
#include
#include
#include
#include
#include
#include


//录音时间
#define LENGTH 3


//采样频率
#define RATE 8000


//量化位数
#define SIZE 16


//声道数目http://ubuntuone.cn/
#define CHANNELS 2


//保存录音的音频数据
unsigned char buf[LENGTH*RATE*SIZE*CHANNELS/8];


int main(void){
//声音设备的文件描述符
int fd;

int arg;
//用于保存ioctl的返回值
int status;


//打开声音设备
fd=open("/dev/dsp",O_RDWR);


if(fd<0){
perror("Cannot open /dev/dsp device");
return 1;
}


//以下设置声卡参数
//设置采样时的量化位数
arg=SIZE;
status=ioctl(fd,SOUND_PCM_WRITE_BITS,&arg);


if(status==-1){
perror("Cannot set SOUND_PCM_WRITE_BITS");
return 1;
}


//设置采样声道数目
arg=CHANNELS;


status=ioctl(fd,SOUND_PCM_WRITE_CHANNELS,&arg);
if(status==-1){
perror("Cannot set SOUND_PCM_WRITE_CHANNELS");
return 1;
}

//设置采样频率
arg=RATE;

status=ioctl(fd,SOUND_PCM_WRITE_RATE,&arg);


if(status==-1){
perror("Cannot set SOUND_PCM_WRITE_RATE");
return 1;
}


//一直录音,直到按下“ Control-C”停止
while(1){
printf("Recording ...:\n");
status=read(fd,buf,sizeof(buf));

if(status==-1){
perror("read wrong number of bytes");
}


printf("Play ...:\n");
status=write(fd,buf,sizeof(buf));
if(status != sizeof(buf)) perror("wrote wrong number of bytes");


//在继续录音前等待回放结束
status=ioctl(fd,SOUND_PCM_SYNC,0);


if(status==-1) perror("Cannot set SOUND_PCM_SYNC");
}
return 0;
}


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Linux下声卡编程(播放指定音频文.. 下一篇Ubuntu 9.04下open函数编译不过的..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: