我用的开发板是MINI2440,内核是linux2.6.29
在对音频设备(/dev/dsp)操作时发现他只能以只读或以只写的方式打开,也就是说不能以读写方式打开。
fd = open("/dev/dsp", O_RDONLY); //打开成功
fd = open("/dev/dsp", O_WRONLY); //打开成功
fd = open("/dev/dsp", O_RDWR); //打开失败
那么如果要实现同时录音与放音的话,只能是分时间片(假设10ms),在每个时间片中以读或以写方式打开设备,然后关闭,这样在很短的时间里,就要进行很多次音频设备的打开各关闭操作,最主要的问题打开和关闭设备在耳机中都有很大的杂音输出,这样的话根本不能正常的进行边录边放音。请高人指点一下,谢谢。
下面是我的代码:
#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 50 /* 存储秒数 */
#define RATE 44000 /* 采样频率 */
#define SIZE 8 /* 量化位数 */
#define CHANNELS 1 /* 声道数目 */
/* 用于保存数字音频数据的内存缓冲区 */
unsigned char buf[LENGTH*RATE*SIZE*CHANNELS/8000];
int main()
{
int fd; /* 声音设备的文件描述符 */
int arg; /* 用于ioctl调用的参数 */
int status; /* 系统调用的返回值 */
while (1) {
/* 打开声音设备 */
fd = open("/dev/dsp", O_RDONLY);
if (fd < 0) {
perror("open of /dev/dsp 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");
/* 循环,直到按下Control-C */
printf("Say something:\n");
status = read(fd, buf, sizeof(buf)); /* 录音 */
if (status != sizeof(buf))
perror("read wrong number of bytes");
close(fd);
//放音--------------------------------------------------------------------
fd = open("/dev/dsp", O_WRONLY);
if (fd < 0) {
perror("open of /dev/dsp 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");
printf("You said:\n");
status = write(fd, buf, sizeof(buf)); /* 回放 */
if (status != sizeof(buf))
perror("wrote wrong number of bytes");
/* 在继续录音前等待回放结束 */
status = ioctl(fd, SOUND_PCM_SYNC, 0);
if (status == -1)
perror("SOUND_PCM_SYNC ioctl failed");
close(fd);
}
}
解决办法是分线程,一个线程以写方式打开,另一个线程以读方式打开,分线程的东西用QT提供的QThread很好做到[ 此帖被panshi5208在2011-02-21 14:11重新编辑 ]