如何在c++中使用ffmpeg动态更改视频的音轨

How to change the audio track of a video on the fly using ffmpeg in c++?

本文关键字:动态 视频 音轨 ffmpeg c++      更新时间:2023-10-16

我正在尝试在android中开发一个媒体播放器应用程序。我使用海豚玩家的代码作为参考。但我不知道如何在播放视频时更改音频和字幕音轨。使用ffmpeg的命令行是可能的,但是如何使用ffmpegc++代码呢?

视频文件是一个包含一堆流的容器。首先,您必须打开视频文件并提取流信息(避免对较小代码进行错误检查):

AVFormatContext *pFormatCtx;
av_open_input_file( &pFormatCtx, argv[1], NULL, 0, NULL );
av_find_stream_info( pFormatCtx );

现在您可以迭代流并找到所有音频流:

for ( i=0; i != pFormatCtx->nb_streams; i++ )
{
   if (pFormatCtx->streams[i]->codec->codec_type==CODEC_TYPE_AUDIO) audioStreams.push_back( i );
}

选择要播放的流,并获取指向编解码器的指针并打开它:

AVCodecContext* aCodecCtx = pFormatCtx->streams[SelectedAudioStream]->codec;
AVCodec* aCodec = avcodec_find_decoder(aCodecCtx->codec_id);
avcodec_open(aCodecCtx, aCodec);

然后像往常一样解码流。