音频 MP2 编码和解码产生一半的数据C++和 FFMPEG

Audio MP2 encoding and decoding producing half data C++ and FFMPEG

本文关键字:数据 C++ FFMPEG 一半 MP2 编码 解码 音频      更新时间:2023-10-16

我有 16 位 PCM 数据,带有立体声设置,我从麦克风中获取。

获得数据后,我使用以下编码器设置对其进行编码

AVCodec* audio_codec = avcodec_find_encoder(AV_CODEC_ID_MP2);
AVCodecContext* audio_codec_ctx = avcodec_alloc_context3(audio_codec);
audio_codec_ctx->bit_rate = 64000;
audio_codec_ctx->channels = 2;
audio_codec_ctx->channel_layout = AV_CH_LAYOUT_STEREO;
audio_codec_ctx->sample_rate = 44100;
audio_codec_ctx->sample_fmt = AV_SAMPLE_FMT_S16;

当我将音频数据传递到编码器时,我看到它每次需要 4608 字节的数据并将其正确编码为 MP2 数据。 麦克风抓取的 PCM 数据为 88320 字节,编码器每次获取 4608 字节并进行压缩。

如果我获取每个已编码的 4608 字节部分,并将其传递到具有与上述相同设置但使用解码器的解码器。

AVCodecID audio_codec_id = AV_CODEC_ID_MP2;
AVCodec * audio_decodec = avcodec_find_decoder(audio_codec_id);
audio_decodecContext = avcodec_alloc_context3(audio_decodec); 
audio_decodecContext->bit_rate = 64000;
audio_decodecContext->channels = 2;
audio_decodecContext->channel_layout = AV_CH_LAYOUT_STEREO;
audio_decodecContext->sample_rate = 44100;
audio_decodecContext->sample_fmt = AV_SAMPLE_FMT_S16;

解码有效并且成功,但是当我查看数据大小时,它正好是编码的 2034 的一半。 我不明白为什么会这样。 考虑到编码器和解码器相同,我会想象我会得到 4608。

谁能阐明为什么会发生这种情况。 我应该设置什么?

应使用 audio_decodecContext->request_sample_fmt 设置请求的解码器示例格式。 sample_fmt由解码器本身设置,并且可能不同,在这种情况下,您应该使用 libswresample 在示例格式之间进行转换。