23,121
社区成员
发帖
与我相关
我的任务
分享
//播放线程
void *StartPlay(void *arg)
{
int dsp_arg = 0;
int fd_wav = open("music.wav", O_RDONLY);
int fd_dsp_w = open("/dev/dsp", O_WRONLY);
if(fd_dsp_w < 0)
{
printf("[Error] Failed to open soundcard in play thread.\n");
}
else
{
printf("[Info] Play dsp file descriptor: %d.\n", fd_dsp_w);
}
//设置位数
dsp_arg = AFMT_S16_LE;
if(ioctl(fd_dsp_w, SNDCTL_DSP_SETFMT, &dsp_arg) == -1)
{
printf("[Error] Failed to set SNDCTL_DSP_SETFMT in play thread.\n");
}
//设置声道数
dsp_arg = 1;
if(ioctl(fd_dsp_w, SNDCTL_DSP_CHANNELS, &dsp_arg) == -1)
{
printf("[Error] Failed to set SNDCTL_DSP_CHANNELS in play thread.\n");
}
//设置采样率
dsp_arg = 11025;
if(ioctl(fd_dsp_w, SNDCTL_DSP_SPEED, &dsp_arg) == -1)
{
printf("[Error] Failed to set SNDCTL_DSP_SPEED in play thread.\n");
}
char buf[2048];
int buf_len = sizeof(buf);
memset(buf, 0, buf_len);
while(1)
{
read(fd_pcm, buf, buf_len); //读取音频文件
write(fd_dsp_w, buf, buf_len); //写入声卡进行播放
}
close(fd_wav);
close(fd_dsp_w);
}
//录音线程
void *StartRecord(void *arg)
{
int dsp_arg = 0;
int fd_rec = open("rec.pcm", O_WRONLY | O_TRUNC);
int fd_dsp_r = open("/dev/dsp", O_RDONLY);
if(fd_dsp_r < 0)
{
printf("[Error] Failed to open soundcard in record thread.\n");
}
else
{
printf("[Info] Record dsp file descriptor: %d.\n", fd_dsp_r);
}
//设置位数
dsp_arg = AFMT_S16_LE;
if(ioctl(fd_dsp_r, SNDCTL_DSP_SETFMT, &dsp_arg) == -1)
{
printf("[Error] Failed to set SNDCTL_DSP_SETFMT in record thread.\n");
}
//设置声道数
dsp_arg = 1;
if(ioctl(fd_dsp_r, SNDCTL_DSP_CHANNELS, &dsp_arg) == -1)
{
printf("[Error] Failed to set SNDCTL_DSP_CHANNELS in record thread.\n");
}
//设置采样率
dsp_arg = 11025;
if(ioctl(fd_dsp_r, SNDCTL_DSP_SPEED, &dsp_arg) == -1)
{
printf("[Error] Failed to set SNDCTL_DSP_SPEED in record thread.\n");
}
char buf[2048];
int buf_len = sizeof(buf);
memset(buf, 0, buf_len);
while(1)
{
//memset(&buf, 0, sizeof(buf));
read(fd_dsp_r, buf, buf_len);
write(fd_rec, buf, buf_len);
}
close(fd_rec);
close(fd_dsp_r);
}
int main(int argc, char const *argv[])
{
pthread_t thd_play;
pthread_t thd_record;
if(pthread_create(&thd_play, NULL, StartPlay, NULL))
{
printf("Failed to create play thread.\n");
exit(1);
}
if(pthread_create(&thd_record, NULL, StartRecord, NULL))
{
printf("Failed to create record thread.\n");
exit(2);
}
while(1)
{
sleep(1);
}
return 0;
}