#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/soundcard.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#define BUFFER_LEN 16*1024
unsigned char ucWAVHeader[] =
{
// RIFF WAVE Chunk
0x52, 0x49, 0x46, 0x46, // "RIFF"
0x00, 0x00, 0x00, 0x00, // =文件总长度 -8
0x57, 0x41, 0x56, 0x45, // "WAVE"
// Format Chunk
0x66, 0x6D, 0x74, 0x20, // "fmt "
0x10, 0x00, 0x00, 0x00, // Chunk 长度,值不变
0x01, 0x00, // 编码方式 一般为1(PCM)
0x02, 0x00, // 声道数目
0x22, 0x56, 0x00, 0x00, // 采样频率
0x44, 0xAC, 0x00, 0x00, // 每秒所需字节数=采样频率*块对齐字节
0x04, 0x00, // 数据对齐字节=每个采样点字节数(byte)*声道数目
0x10, 0x00, // 每个采样点占用多少bit位
// Fact Chunk
0x66, 0x61, 0x63, 0x74, // "fact" 这个chunk 一般不动
0x04, 0x00, 0x00, 0x00, // 块长度
0x00, 0xBE, 0x00, 0x00,
// Data Chunk
0x64, 0x61, 0x74, 0x61, // "data"
0x00, 0x00, 0x00, 0x00, // 块长度 = 实际PCM数据的长度
};
int main(int argc, char *argv[])
{
if(argc<2){
printf("usage:\n\t oss_test xxx.wav\n");
return 0;
}
int i;
int wav_fd=open(argv[1],O_RDONLY);
if (wav_fd<=0) {
perror("open wav_fd");
return -1;
}
char buffer[BUFFER_LEN];
int want_len=BUFFER_LEN,real_len;
read(wav_fd,ucWAVHeader,sizeof(ucWAVHeader));
int oss_fd = open("/dev/dsp", O_WRONLY, 0);//打开OSS
if (oss_fd<=0) {
perror("open");
return -1;
}
i = AFMT_S16_LE;
if (ioctl(oss_fd, SNDCTL_DSP_SETFMT, &i) < 0) {//设置帧格式
perror("");
return -1;
}
if (i != AFMT_S16_LE) {
perror("");
return -1;
}
i=*(short*)(ucWAVHeader+22);
printf("channel count:%d\n",i);
if (ioctl(oss_fd, SNDCTL_DSP_CHANNELS, &i) < 0) {//设置通道数
perror("");
return -1;
}
i=9;//dma frament size=2^9
i |= 4<< 16; //dma frament count
if (ioctl(oss_fd, SNDCTL_DSP_SETFRAGMENT, &i) < 0) {//dma 缓冲区设置
perror("");
return -1;
}
i = *(int*)(ucWAVHeader+24);
printf("sample rate:%d\n",i);
if (ioctl(oss_fd, SNDCTL_DSP_SPEED, &i) < 0) {//设置采样频率
perror("");
return -1;
}
printf("----------play start------------\n");
/*
*在向DSP设备写入数据时,数字信号会经过D/A转换器变成模拟信号,然后产生出声音。应用程序写入数据的速度同样应该与声卡的采样频率相匹配,否则过慢的话会产生声音暂停或者停顿的现象,过快的话又会被内核中的声卡驱动程序阻塞,直到硬件有能力处理新的数据为止。
*/
while((real_len=read(wav_fd,buffer,want_len))!=0){
write(oss_fd,buffer,real_len);
}
printf("----------play end------------\n");
close(wav_fd);
close(oss_fd);
return 0;
}