Chinaunix首页 | 论坛 | 博客
  • 博客访问: 583717
  • 博文数量: 109
  • 博客积分: 1463
  • 博客等级: 上尉
  • 技术积分: 859
  • 用 户 组: 普通用户
  • 注册时间: 2011-07-22 13:21
个人简介

希望和广大热爱技术的童鞋一起交流,成长。

文章分类

全部博文(109)

文章存档

2017年(1)

2016年(2)

2015年(18)

2014年(1)

2013年(9)

2012年(15)

2011年(63)

分类: LINUX

2011-11-07 09:09:23

  参考教材:<Linux编程技术详解>杜华编著
     页码:P186
     将音频文件写入声卡的设备文件中可以实现音频文件的播放。而使用read函数来读取声卡设备文件中的内容,则可以实现录音功能。下面的程序代码实现了在Linux系统下使用声卡设备的录音功能。
     具体代码如下:
//p6.8.c声卡录音功能:
  1. #include<unistd.h>
  2. #include<fcntl.h>
  3. #include<sys/types.h>
  4. #include<sys/ioctl.h>
  5. #include<stdlib.h>
  6. #include<stdio.h>
  7. #include<linux/soundcard.h>

  8. //录音时间
  9. #define LENGTH 3

  10. //采样频率
  11. #define RATE 8000

  12. //量化位数
  13. #define SIZE 16

  14. //声道数目
  15. #define CHANNELS 2

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

  18. int main(void){
  19.    //声音设备的文件描述符
  20.    int fd;
  21.   
  22.    int arg;
  23.    //用于保存ioctl的返回值
  24.    int status;

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

  27.    if(fd<0){
  28.       perror("Cannot open /dev/dsp device");
  29.       return 1;
  30.    }

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

  35.    if(status==-1){
  36.       perror("Cannot set SOUND_PCM_WRITE_BITS");
  37.       return 1;
  38.    }

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

  41.    status=ioctl(fd,SOUND_PCM_WRITE_CHANNELS,&arg);
  42.    if(status==-1){
  43.       perror("Cannot set SOUND_PCM_WRITE_CHANNELS");
  44.       return 1;
  45.    }
  46.   
  47.    //设置采样频率
  48.    arg=RATE;
  49.   
  50.    status=ioctl(fd,SOUND_PCM_WRITE_RATE,&arg);

  51.    if(status==-1){
  52.      perror("Cannot set SOUND_PCM_WRITE_RATE");
  53.      return 1;
  54.    }

  55.    //一直录音,直到按下“ Control-C”停止
  56.    while(1){
  57.      printf("Recording ...:\n");
  58.      status=read(fd,buf,sizeof(buf));
  59.     
  60.      if(status==-1){
  61.         perror("read wrong number of bytes");
  62.      }

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

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

  68.      if(status==-1) perror("Cannot set SOUND_PCM_SYNC");
  69.    }
  70.    return 0;
  71. }

 
阅读(1823) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~