1)音频设备只能以O_WRONLY或者O_RDONLY方式打开,不能使用O_RDWR方式打开,因为不支持同时录音和放音。
2)使用方法举例"./oss /tmp/test.wav 22050" ,会自动录音2MB,再将其播放出来。
3)支持调整音频采样率:支持44100、22050、11025和8000四种采样率。
以下为测试程序源码
==================================================================================
//注意!音频设备只能以O_WRONLY或者O_RDONLY方式打开,不能使用O_RDWR方式打开,因为不支持同时录音和放音。
#include <sys/ioctl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/soundcard.h>
2)使用方法举例"./oss /tmp/test.wav 22050" ,会自动录音2MB,再将其播放出来。
3)支持调整音频采样率:支持44100、22050、11025和8000四种采样率。
以下为测试程序源码
==================================================================================
//注意!音频设备只能以O_WRONLY或者O_RDONLY方式打开,不能使用O_RDWR方式打开,因为不支持同时录音和放音。
#include <sys/ioctl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/soundcard.h>
#define BUF_SIZE 4096
#define DEVICE_NAME "/dev/dsp"
int audio_fd; //声卡
FILE *file_fd; //文件
int file_len; //文件长度
unsigned char audio_buffer[BUF_SIZE];
FILE *file_fd; //文件
int file_len; //文件长度
unsigned char audio_buffer[BUF_SIZE];
unsigned char *file_name_creat;
unsigned int audio_rate;
unsigned int audio_rate;
int main(int argc, char *argv[])
{
file_name_creat = argv[1];
sscanf(argv[2],"%d", &audio_rate);
/*打开音频设备,准备音*/
if ((audio_fd = open(DEVICE_NAME, O_WRONLY)) == -1)
{
printf("open error\n");
return -1;
}
/***1.设置采样格式*/
int format = AFMT_S16_LE;
if (ioctl(audio_fd, SNDCTL_DSP_SETFMT, &format) == -1)
{
/* fatal error */
printf("SNDCTL_DSP_SETFMT error\n");
return -1;
}
/***2.设置通道数*/
int channels = 2; /* 1=mono, 2=stereo */
if (ioctl(audio_fd, SNDCTL_DSP_CHANNELS, &channels) == -1)
{
/* Fatal error */
printf("SNDCTL_DSP_CHANNELS error");
return -1;
}
/***3.设置采样速率*/
int speed = audio_rate;
if (ioctl(audio_fd, SNDCTL_DSP_SPEED, &speed)==-1)
{
/* Fatal error */
printf("SNDCTL_DSP_SPEED error\n");
return -1;
}
printf("the wav speed is %d\n",speed);
/*打开并计算文件长度*/
file_fd = fopen(file_name_creat, "r");
fseek(file_fd,0,SEEK_END); //定位到文件末
file_len = ftell(file_fd); //文件长度
int loops = file_len/BUF_SIZE;
/*重新定位到文件头*/
fclose(file_fd);
file_fd = fopen(file_name_creat, "r");
/*播放wav文件*/
int i;
for(i=0;i<loops;i++)
{
fread(audio_buffer, BUF_SIZE, 1, file_fd);
write(audio_fd,audio_buffer,BUF_SIZE);
}
/*关闭设备和文件*/
fclose(file_fd);
close(audio_fd);
return 0;
}
原文链接
http://hi.baidu.com/falimon_7/blog/item/dc399621a6f717fed6cae211.html
int speed = audio_rate;
if (ioctl(audio_fd, SNDCTL_DSP_SPEED, &speed)==-1)
{
/* Fatal error */
printf("SNDCTL_DSP_SPEED error\n");
return -1;
}
printf("the wav speed is %d\n",speed);
/*打开并计算文件长度*/
file_fd = fopen(file_name_creat, "r");
fseek(file_fd,0,SEEK_END); //定位到文件末
file_len = ftell(file_fd); //文件长度
int loops = file_len/BUF_SIZE;
/*重新定位到文件头*/
fclose(file_fd);
file_fd = fopen(file_name_creat, "r");
/*播放wav文件*/
int i;
for(i=0;i<loops;i++)
{
fread(audio_buffer, BUF_SIZE, 1, file_fd);
write(audio_fd,audio_buffer,BUF_SIZE);
}
/*关闭设备和文件*/
fclose(file_fd);
close(audio_fd);
return 0;
}