写一个c++的基于ffmpeg的音频编码程序
时间: 2023-03-12 12:15:42 浏览: 126
下面是一个基于 FFmpeg 的 C 语言音频编码程序:
#include <libavcodec/avcodec.h>
#include <libavutil/opt.h>
#include <libavutil/audio_fifo.h>int main(int argc, char *argv[])
{
//声明编码器上下文
AVCodecContext *codecContext = NULL;
//声明编码器
AVCodec *codec = NULL;
int ret = 0;
//声明音频采样帧
AVFrame *frame = NULL;
int gotFrame = 0; //初始化编码器上下文
codecContext = avcodec_alloc_context3(codec);
if (!codecContext) {
printf("Could not allocate a codec context\n");
return -1;
} //选择编码器
codec = avcodec_find_encoder(AV_CODEC_ID_MP3);
if (!codec) {
printf("Could not find a suitable encoder\n");
return -1;
} //设置编码器参数
codecContext->bit_rate = 64000;
codecContext->sample_rate = 44100;
codecContext->channels = 2;
codecContext->channel_layout = AV_CH_LAYOUT_STEREO;
codecContext->sample_fmt = AV_SAMPLE_FMT_S16; //打开编码器
ret = avcodec_open2(codecContext, codec, NULL);
if (ret < 0) {
printf("Could not open the codec\n");
return -1;
} //分配音频采样帧
frame = av_frame_alloc();
if (!frame) {
printf("Could not allocate an audio frame\n");
return -1;
} //设置音频采样帧的参数
frame->nb_samples = codecContext->frame_size;
frame->format = codecContext->sample_fmt;
frame->channel_layout = codecContext->channel_layout; //分配采样帧的缓冲区
ret = av_frame_get_buffer(frame, 0);
if (ret < 0) {
printf("Could not allocate the audio data buffers\n");
return -1;
} //读取音频采样数据
//... //编码音频采样帧
ret = avcodec_encode_audio2(codecContext, &pkt, frame, &gotFrame);
if (ret < 0) {
printf("Could not encode the frame\n");
return -1;
} //释放资源
av_frame_free(&frame);
avcodec_free_context(&codecContext); return 0;
}
阅读全文