avcodec_open2返回值为-22

函数:int avcodec_open2(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options);

头文件:Avcodec.h

官方解释:

/**
 * Initialize the AVCodecContext to use the given AVCodec. Prior to using this
 * function the context has to be allocated with avcodec_alloc_context3().
 *
 * The functions avcodec_find_decoder_by_name(), avcodec_find_encoder_by_name(),
 * avcodec_find_decoder() and avcodec_find_encoder() provide an easy way for
 * retrieving a codec.
 *
 * @warning This function is not thread safe!
 *
 * @note Always call this function before using decoding routines (such as
 * @ref avcodec_receive_frame()).
 *
 * @code
 * avcodec_register_all();
 * av_dict_set(&opts, "b", "2.5M", 0);
 * codec = avcodec_find_decoder(AV_CODEC_ID_H264);
 * if (!codec)
 *     exit(1);
 *
 * context = avcodec_alloc_context3(codec);
 *
 * if (avcodec_open2(context, codec, opts) < 0)
 *     exit(1);
 * @endcode
 *
 * @param avctx The context to initialize.
 * @param codec The codec to open this context for. If a non-NULL codec has been
 *              previously passed to avcodec_alloc_context3() or
 *              for this context, then this parameter MUST be either NULL or
 *              equal to the previously passed codec.
 * @param options A dictionary filled with AVCodecContext and codec-private options.
 *                On return this object will be filled with options that were not found.
 *
 * @return zero on success, a negative value on error
 * @see avcodec_alloc_context3(), avcodec_find_decoder(), avcodec_find_encoder(),
 *      av_dict_set(), av_opt_find().
 */

问题:AVCodecContext和AVCodec两个结构体都赋值的前提下,该函数在编码时莫名其妙,返回负数。究其原因主要是由于AVCodecContext中赋值的不匹配,主要设置参数:codec_type、sample_fmt、channel_layout、sample_rate、channels。本人总结了PCM->OPUS和PCM转MP3参数的设置,如下表所示:

1、PCM转OPUS的参数设置:

AVMEDIA_TYPE_AUDIO

          codec_type

AV_SAMPLE_FMT_S16

sample_fmt

AV_CH_LAYOUT_STEREO

channel_layout

48000

sample_rate

2

           channels

2、PCM转MP3

AVMEDIA_TYPE_AUDIO

          codec_type

AV_SAMPLE_FMT_S16P

sample_fmt

AV_CH_LAYOUT_STEREO

channel_layout

44100

sample_rate

2

           channels


你可能感兴趣的:(音视频:ffmpeg,ffmpeg的使用)