fortea
fortea

Reputation: 369

C: playing audio loops in linux

I have a buffer of int16_t with some audio PCM data in it. I need to play the buffer repetitively from a point a to a point b, so that you hear an infinite audio loop.

I found that the easiest way to play sound is by using libao, but I agree with any other method. This is my code:

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;  
}

The problem is that I hear a period of silence between the end and the start of the loop. Because I'm using this code to testing other code, I absolutely need to know if it could be caused by an incorrect use of libao.

Upvotes: 1

Views: 1938

Answers (1)

clarry
clarry

Reputation: 26

Yes, it absolutely could be caused by incorrect use of libao. Please remove the +1 from the ao_play() call, like so:

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

Upvotes: 1

Related Questions