Search code examples
caudioencodingmp3lame

Encoding Audio with lame: Converting 32bit float to mp3


I am having difficulties converting 32 bit float audio to mp3 using lame. I am currently able to convert the audio to an mp3 but the output has evenly spaced gaps that appear like they are inserted between the proper output (none of the expected output is missing).

Below is an image of the time-line for the outputted audio in Audacity Audio timeline

Below is the code I am using:

#include <stdio.h>
#include <lame/lame.h>

int main(void)
{
    int read, write;

    FILE *pcm = fopen("file.pcm", "rb");
    FILE *mp3 = fopen("file.mp3", "wb");

    const int PCM_SIZE = 10000;
    const int MP3_SIZE = 10000;
    unsigned char mp3_buffer[MP3_SIZE];

    float pcm_buffer[PCM_SIZE*2];

    lame_t lame = lame_init();
    lame_set_in_samplerate(lame, (48000/2)); //The sampling rate of the input file is 48MHz
    //but the output sounds like its on fast-forward when input sample rate is set to 48MHz
    lame_set_VBR(lame, vbr_off); // also tried vbr_default
    lame_set_out_samplerate(lame, 16000);
    lame_init_params(lame);

    do {
        read = fread(pcm_buffer, sizeof(float), PCM_SIZE, pcm);
        printf("read = %d\n",read);
        if (read == 0)
            write = lame_encode_flush(lame, mp3_buffer, MP3_SIZE);
        else
            write = lame_encode_buffer_interleaved_ieee_float(lame, pcm_buffer, read, mp3_buffer, MP3_SIZE);
        fwrite(mp3_buffer, write, 1, mp3);
    } while (read != 0);

    lame_close(lame);
    fclose(mp3);
    fclose(pcm);
    return 0;
}

Solution

  • I got it working, I just needed to change from using the lame_encode_buffer_interleaved_ieee_float to using the lame_encode_buffer_ieee_float function