延迟后snd_pcm_writei无法正常工作

时间:2015-01-28 15:44:36

标签: c linux alsa

我试图使用ALSA生成一声哔声。应该产生2声蜂鸣声,第二声延迟1秒后。我的代码如下所示。

if ((err = snd_pcm_prepare (playback_handle)) < 0) {
    printf("cannot prepare audio interface for use \n");
    return -1;
}


for (i = 0; i < TABLE_SIZE; i ++){
    samples[i] = 100*sin(2.0*pi*f*(i/44100.0));
    if ((err = snd_pcm_writei (playback_handle, &samples[i], 4)) != 4) {
        printf("write to audio interface failed \n");
        return -1;
    }
}

//snd_pcm_drain(playback_handle);

printf("ending beep !!! \n");
sleep(1);

if ((err = snd_pcm_prepare (playback_handle)) < 0) {
    printf("cannot prepare audio interface for use \n");
    return -1;
}
for (i = 0; i < TABLE_SIZE; i ++){
    samples[i] = 100*sin(2.0*pi*f*(i/44100.0));
    if ((err = snd_pcm_writei (playback_handle, &samples[i], 4)) != 4) {
        printf("write to audio interface failed \n");
        return -1;
    }
}

这里听到第一声嘟嘟声,但第二声蜂鸣声不正常。任何人都可以帮我解决这个问题。

1 个答案:

答案 0 :(得分:0)

snd_pcm_write*()只是将样本写入缓冲区,但是当所有样本都在缓冲区中时立即返回。

要等到缓冲区中的所有样本都播放完毕,请拨打snd_pcm_drain()