Chinaunix

标题: Linux环境下用c语言写的播放wav文件的小程序[转] [打印本页]

作者: peijieking    时间: 2009-12-30 16:35
标题: Linux环境下用c语言写的播放wav文件的小程序[转]

http://blog.csdn.net/noah1987/archive/2008/10/21/3118934.aspx
本程序可以读取.wav文件,然后进行播放。
使用前,请确认您是否安装音频驱动。
确认方法:cat /etc/sndstat,如果显示无此设备,则没有安装驱动。
安装驱动很简单,到oss.com上下载音频驱动,然后按照网上的教程进行就可以了。
源代码如下:
#include
#include
#include
#include
#include
#include
#include
/* 下面的三个参数是跟具体文件相关的,文件什么样,就要设置成什么样 */
#define RATE 11025   
#define SIZE 16     
#define CHANNELS 1  // 1表示单声道,2为立体声
/* ................ */
unsigned char buf[RATE*SIZE/8]; //buf里面正好放一秒钟的音频,下面的计时还要用
int main()
{
    int fd;
    int wavfd; //wav文件的描述符
    int arg;        /* ..ioctl..... */
    int status;   /* ........ */
                /* ...... */
    fd = open("/dev/dsp", O_RDWR);      
    if (fd
/* .......... */
    arg = SIZE;
    status = ioctl(fd, SOUND_PCM_WRITE_BITS, &arg);
    if (status == -1)
         perror("SOUND_PCM_WRITE_BITS ioctl failed");
    if (arg != SIZE)
         perror("unable to set sample size");
  
/* .......... */
    arg = CHANNELS;
    status = ioctl(fd, SOUND_PCM_WRITE_CHANNELS, &arg);
    if (status == -1)
        perror("SOUND_PCM_WRITE_CHANNELS ioctl failed");
    if (arg != CHANNELS)
        perror("unable to set number of channels");
  
/* .......... */
     arg = RATE;
         status = ioctl(fd, SOUND_PCM_WRITE_RATE, &arg);
     if (status == -1)
         perror("SOUND_PCM_WRITE_WRITE ioctl failed");
  
    /* 从wav文件中读buf大小的内容,然后写入/etc/dsp中,直到文件结束 */
     int time = 0; //动态显示播放时间用

     while (status = read(wavfd, buf, sizeof(buf)) > 0) {
         write(fd, buf, sizeof(buf));
         printf("%ds, enjoy ...\n",time++);  

          /* 以下三句,用于在更改播放文件的参数时,播放掉缓冲区内的内容,可以用,更保险*/     
         /*status = ioctl(fd, SOUND_PCM_SYNC, 0);
           if (status == -1)
               perror("SOUND_PCM_SYNC ioctl failed");
          */         
        }
}
本程序中需要一个.wav文件才能播放,你可以到百度mp3上去搜索一个.wav文件,放到程序目录下。然后,把程序中的文件名改成该音频的文件名。
ps:可以用file 文件名命令来查看该wav文件的属性,以便据此来更改程序中的播放参数。
本文来自CSDN博客,转载请标明出处:
http://blog.csdn.net/noah1987/archive/2008/10/21/3118934.aspx


本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u2/88620/showart_2135653.html




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2