C:在linux中播放音频循环

时间:2013-03-10 13:40:21

标签: c linux audio

我有一个int16_t的缓冲区,里面有一些音频PCM数据。我需要从a点到b点重复播放缓冲区,这样你才能听到无限的音频循环。

我发现播放声音的最简单方法是使用libao,但我同意任何其他方法。 这是我的代码:

int play(int a, int b, char *buf);

int main()
{
        int16_t *buf;  /*my buffer*/
        int a, b;
        /* a and b are the indexes of the buffer; 
         * because libao wants a buffer of char, 
         * and buf points to of int16_t, I'll pass 
         * the value a and b multiplied with 2.
         */ 

        [···]

        play(2*a, 2*b, (char *) buf);
        return 0;
}
int play(int a, int b, char *buf)
{  
        ao_device *device;  
        ao_sample_format format;  
        int default_driver;   
        /* -- Initialize -- */
        fprintf(stderr, "libao example program\n");  
        ao_initialize();  
        /* -- Setup for default driver -- */  
        default_driver = ao_default_driver_id();  
        memset(&format, 0, sizeof(format));  
        format.bits = 16;  
        format.channels = 1;  
        format.rate = 44100;  
        format.byte_format = AO_FMT_LITTLE;
        /* -- Open driver -- */  
        device = ao_open_live(default_driver, &format, NULL /* no options */);  
        if (device == NULL) {  
            fprintf(stderr, "Error opening device.\n");  
            exit(1);  
        }  
        /* -- Play the infinite loop -- */
        for (;;){
            ao_play(device, buf+a, b-a+1);
            /*buf+a is the start of the loop, b-a+1 the number of byte to play--edited*/
        }
        /* -- Close and shutdown -- */  
        ao_close(device);  
        ao_shutdown();  
    return 0;  
}

问题是我在循环结束和开始之间听到一段时间的沉默。因为我正在使用此代码来测试其他代码,所以我绝对需要知道它是否可能是由于libao的错误使用造成的。

1 个答案:

答案 0 :(得分:1)

是的,绝对可能是由于错误使用libao造成的。请从ao_play()调用中删除+1,如下所示:

ao_play(device, buf+a, b-a);