Linux音频编程指南

来源:互联网 发布:matlab字符分割算法 编辑:程序博客网 时间:2024/06/15 20:02

 http://www.hzlitai.com.cn/article/ARM9-article/example/1518.html

一个测试通过的音频播放程序


#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <stdlib.h>
#include <stdio.h>
#include <linux/soundcard.h>

#define LENGTH 3 /* 存储秒数 */
#define RATE 8000 /* 采样频率 */
#define SIZE 8 /* 量化位数 */
#define CHANNELS 1 /* 声道数目 */

/* 用于保存数字音频数据的内存缓冲区 */
unsigned char buf[LENGTH*RATE*SIZE*CHANNELS/8];

int main()
{

int fd;/* 声音设备的文件描述符 */
int id; /*声音输出文件描述符*/
int arg;/* 用于ioctl调用的参数 */
int status; /* 系统调用的返回值 */
int i;
int j;



/* 打开声音设备 */
fd = open("/dev/dsp", O_RDWR);//arm下的音频文件是"/dev/sound/dsp";
if (fd < 0) {
perror("open of /dev/dsp failed");
exit(1);
}
/*打开输出文件*/
id=open("Music.wav",O_RDWR);
if(id < 0){
perror("open of sound file failed");
exit(1);
}
/* 设置采样时的量化位数 */
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");

/* 读取一定数量的音频数据,并将之写到输出文件中去 */
for(i=0;i<10;i ){
j=read(id, buf, sizeof(buf));
if (j > 0){
write(fd, buf, j); /* 放音 */
}
}

/* 关闭输入、输出文件 */
close(fd);
close(id);
return 1;
}
原创粉丝点击