使用OSS播放WAV音频

#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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值