Chinaunix首页 | 论坛 | 博客
  • 博客访问: 583834
  • 博文数量: 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:12:30

参考教材:<Linux编程技术详解>杜华编著
   页码:P184
   程序实现了在Linux下播放Online.wav的功能。程序首先调用fstat函数获得文件相关信息(主要是文件大小信息)。通过malloc函数分配指定的内存空间,并将online.wav读入内存;然后,打开声卡设备文件,设置声卡参数;再调用write函数完成文件的播放。
    具体可行的代码如下:
//p6.7.c
  1. #include<unistd.h>
  2. #include<fcntl.h>
  3. #include<sys/types.h>
  4. #include<sys/stat.h>
  5. #include<stdlib.h>
  6. #include<stdio.h>
  7. #include<linux/soundcard.h>

  8. #define Audio_Device "/dev/dsp"

  9. //不同的声音有着不同的播放参数,这些参数可以使用file命令获得

  10. #define Sample_Size 16 //there're two kinds of bits,8 bits and 16 bits
  11. #define Sample_Rate 8000 //sampling rate

  12. int play_sound(char *filename){
  13.     struct stat stat_buf;
  14.     unsigned char * buf = NULL;
  15.     int handler,fd;
  16.     int result;
  17.     int arg,status;
  18.    
  19.     //打开声音文件,将文件读入内存
  20.     fd=open(filename,O_RDONLY);
  21.     if(fd<0) return -1;
  22.     if(fstat(fd,&stat_buf)){
  23.         close(fd);
  24.         return -1;
  25.     }

  26.     if(!stat_buf.st_size){
  27.         close(fd);
  28.         return -1;
  29.    }
  30.    buf=malloc(stat_buf.st_size);
  31.    if(!buf){
  32.       close(fd);
  33.       return -1;
  34.    }

  35.    if(read(fd,buf,stat_buf.st_size)<0){
  36.       free(buf);
  37.       close(fd);
  38.       return -1;
  39.    }

  40.    //打开声卡设备,并设置声卡播放参数,这些参数必须与声音文件参数一致
  41.    handler=open(Audio_Device,O_WRONLY);
  42.    if(handler==-1){
  43.        perror("open Audio_Device fail");
  44.        return -1;
  45.    }
  46.   
  47.    arg=Sample_Rate;
  48.    status=ioctl(handler,SOUND_PCM_WRITE_RATE,&arg);
  49.    if(status==-1){
  50.       perror("error from SOUND_PCM_WRITE_RATE ioctl");
  51.       return -1;
  52.    }

  53.    arg=Sample_Size;
  54.    status=ioctl(handler,SOUND_PCM_WRITE_BITS,&arg);
  55.    if(status==-1){
  56.       perror("error from SOUND_PCM_WRITE_BITS ioctl");
  57.       return -1;
  58.    }
  59.   
  60.    result=write(handler,buf,stat_buf.st_size);
  61.    if(result==-1){
  62.       perror("Fail to play the sound!");
  63.       return -1;
  64.    }

  65.    free(buf);
  66.    close(fd);
  67.    close(handler);
  68.    return result;
  69. }

  70. void main(void)
  71. {
  72.    play_sound("/root/Online.wav");
  73. }
首先必须在/root/目录下存在Online.wav文件,这样运行该代码生成的二进制可执行文件时才可以播放该文件。
阅读(1487) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~