[Libav-user] Convert from PCM_F32LE to PCM_S16LE

Thiago Correa thiago.correa at gmail.com
Sat Apr 25 04:57:44 EEST 2020


Hi,

    I’m writing a program to read from audio input on macOS (av_find_input_format("avfoundation”)) which is PCM_F32LE according to the context (codec_id:AV_CODEC_ID_PCM_F32LE) and I want for simplicity sake just save it to file with fwrite in PCM_S16LE. My first attempt was try to use an encoder but didn’t seem to work. Then I found some information on swr_convert and it seems like that is the right way to convert my audio but my resulting file when played with ffplay sounds like the audio was running faster than expected.

Basically what I’m doing is:

    SwrContext* au_convert_ctx = swr_alloc();
    au_convert_ctx = swr_alloc_set_opts( au_convert_ctx, AV_CH_LAYOUT_STEREO, AV_SAMPLE_FMT_S16, output.audio_sample_rate,
        in_channel_layout, input.audioCodecContext->sample_fmt, input.audioCodecContext->sample_rate, 0, NULL);
    swr_init(au_convert_ctx);

Then after reading an AVPacket with av_read_frame/avcodec_decode_audio4:

    auto ret = swr_convert( au_convert_ctx, &audioOutputBuffer, out_nb_samples, (const uint8_t **)&audioFrame->extended_data[0] , audioFrame->nb_samples );
                
    audioOutputBufferSize = av_samples_get_buffer_size(nullptr, out_channels, ret, AV_SAMPLE_FMT_S16, 1);
    printf("Write Audio frame %3d (size= %2d)\n", j++, audioOutputBufferSize);
    fwrite( audioOutputBuffer, 1, audioOutputBufferSize, f );

   Any advice would be greatly appreciated.

Kind Regards,
    Thiago A. Correa



More information about the Libav-user mailing list