Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1250784
  • 博文数量: 548
  • 博客积分: 7597
  • 博客等级: 少将
  • 技术积分: 4224
  • 用 户 组: 普通用户
  • 注册时间: 2010-12-15 13:21
个人简介

嵌入式软件工程师&&太极拳

文章分类

全部博文(548)

文章存档

2014年(10)

2013年(76)

2012年(175)

2011年(287)

分类: LINUX

2014-01-09 10:51:21


点击(此处)折叠或打开

  1. /* Linux
  2. * --Mao
  3. *
  4. * 播放音频文件要用ioctl函数设置使播放参数与音频文件相同
  5. * 设置声卡采样频率 arg = 16; ioctl(handler,SOUND_PCM_WRITE_BITS,&arg);
  6. *
  7. *
  8. *
  9. */
  10.    
  11. #include <stdio.h>
  12. #include <fcntl.h>
  13. #include <sys/types.h>
  14. #include <sys/ioctl.h>
  15. #include <sys/stat.h>
  16. #include <stdlib.h>
  17. #include <unistd.h>
  18. #include <linux/soundcard.h>
  19.    
  20. #define Audio_Device "/dev/dsp"
  21.    
  22.     /*
  23.     不同的声音有不同的播放参数,这些参数可以使用file命令获得
  24.     */
  25.    
  26. #define Sample_Size 16
  27. #define Sample_Rate 44100
  28.    
  29. int play_sound(char *filename)
  30. {
  31.     struct stat stat_buf;
  32.     unsigned char *buf = NULL;
  33.     int handler,fd;
  34.     int result;
  35.     int arg,status;
  36.     //打开声音文件,将文件读入内存
  37.     fd = open(filename,O_RDONLY);
  38.     if(fd < 0)
  39.         return -1;
  40.     if(fstat(fd,&stat_buf))
  41.     {
  42.         close(fd);
  43.         return -1;
  44.     }
  45.     if(!stat_buf.st_size)
  46.     {
  47.         close(fd);
  48.         return -1;
  49.     }
  50.    
  51.     buf = malloc(stat_buf.st_size);
  52.     if(!buf)
  53.     {
  54.         close(fd);
  55.         return -1;
  56.     }
  57.     if(read(fd,buf,stat_buf.st_size) < 0)
  58.     {
  59.         free(buf);
  60.         close(fd);
  61.         return -1;
  62.     }
  63.    
  64.     /*
  65.     打开声卡设备,并设置声卡播放参数,这些参数必须与声音文件参数一致
  66.     */
  67.    
  68.     handler = open(Audio_Device,O_WRONLY);
  69.     if(handler == -1)
  70.     {
  71.         perror("Cannot open the Audio_Device");
  72.         return -1;
  73.     }
  74.    
  75.     arg = Sample_Rate;
  76.     status = ioctl(handler,SOUND_PCM_WRITE_RATE,&arg);
  77.     if(status == -1)
  78.     {
  79.         perror("error from SOUND_PCM_WRITE_RATE ioctl");
  80.         return -1;
  81.     }
  82.    
  83.     arg = Sample_Size;
  84.     status = ioctl(handler,SOUND_PCM_WRITE_BITS,&arg);
  85.     if(status == -1)
  86.     {
  87.         perror("error from SOUND_PCM_WRITE_BITS ioctl");
  88.         return -1;
  89.     }
  90.    
  91.     result = write(handler,buf,stat_buf.st_size);
  92.     if(result == -1)
  93.     {
  94.         perror("Fail to play the sound");
  95.         return -1;
  96.     }
  97.     free(buf);
  98.     close(fd);
  99.     close(handler);
  100.     return result;
  101. }
  102.    
  103. void main(void)
  104. {
  105.     play_sound("windowXp.wav");
  106. }

阅读(1695) | 评论(0) | 转发(0) |
0

上一篇:Mini2440学习 GPIO

下一篇:没有了

给主人留下些什么吧!~~