我正在开发使用libavcodec库的库。
我尝试使用opus编解码器对音频帧进行编码,但在avcodec_open2(…)之后,我得到了这个日志[opus @ 0x2335f30] The encoder 'opus' is experimental but experimental codecs are not enabled, add '-strict -2' if you want to use it.
另外,当尝试av_fill_audio_frame(..)时,我得到这个错误Invalid argument
我的代码:
#include <libavcodec/avcodec.h>
#include "libavutil/opt.h"
#include <libavformat/avformat.h>
AVFrame *audio_frame = NULL;
AVPacket *audio_packet = NULL;
AVCodecContext *audio_encoder_codec_context = NULL;
AVCodec *audio_encoder_codec = NULL;
void init(){
audio_frame = av_frame_alloc();
audio_packet = av_packet_alloc();
audio_encoder_codec = avcodec_find_encoder(AV_CODEC_ID_OPUS);
audio_encoder_codec_context = avcodec_alloc_context3(audio_encoder_codec);
audio_encoder_codec_context->time_base = (AVRational){1,25};
audio_encoder_codec_context->sample_rate = audio_sample_rate;
audio_encoder_codec_context->sample_fmt = (enum AVSampleFormat) audio_sample_format == 0 ? AV_SAMPLE_FMT_U8 : AV_SAMPLE_FMT_S16;
audio_encoder_codec_context->channels = 1;
audio_encoder_codec_context->channel_layout = AV_CH_LAYOUT_MONO;
audio_encoder_codec_context->codec_type = AVMEDIA_TYPE_AUDIO;
audio_encoder_codec_context->extradata = NULL;
avcodec_open2(audio_encoder_codec_context,audio_encoder_codec,NULL);
audio_frame_size = av_samples_get_buffer_size(
NULL,
audio_encoder_codec_context->channels,
audio_sample_rate,
audio_encoder_codec_context->sample_fmt,
1
);
audio_frame_buffer = (uint8_t*) av_malloc((audio_frame_size)*sizeof(uint8_t));
}
void encode(uint8_t *frame,int frame_size,uint8_t **packet, int *packet_size){
memcpy(audio_frame_buffer, frame, (size_t) frame_size);
av_init_packet(audio_packet);
int isFin = 0;
int r = avcodec_fill_audio_frame(audio_frame,audio_encoder_codec_context->channels,audio_encoder_codec_context->sample_fmt,audio_frame_buffer,audio_frame_size,0);
printf("ERROR = %s",av_err2str(r));
avcodec_encode_audio2(audio_encoder_codec_context,audio_packet,audio_frame,&isFin);
*packet = audio_packet->data;
*packet_size = audio_packet->size;
}
int main(){
init();
uint8_t *packet = NULL;
int size = 0;
encode(".....",44100,packet,size);
}
最佳答案
invalid_argument
错误可以通过在nb_samples
上设置frame
来解决--在设置之前,我也会得到这个错误。示例代码和输出:
AVFrame *frame = av_frame_alloc();
int ret = avcodec_fill_audio_frame(frame, channels, fmt, frame_buffer, frame_size, 0);
if (ret < 0)
{
printf("ERROR = %s\n", av_err2str(ret));
}
else
{
printf("Success (%i bytes required to allocate)\n", ret);
}
产量:
ERROR = Invalid argument
而当
nb_samples
设置正确时:AVFrame *frame = av_frame_alloc();
frame->nb_samples = 48000;
int ret = avcodec_fill_audio_frame(frame, channels, fmt, frame_buffer, frame_size, 0);
// etc...
结果:
Success (192000 bytes required to allocate)
关于c - 作品严格标志,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44978438/