av_find_best_stream()函数就是要获取音视频对应的stream_index。
#include <iostream>
#ifdef __cplusplus
extern "C" {
#endif
#include <libavutil/avutil.h>
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#ifdef __cplusplus
}
#endif
int main()
{
//std::cout <<"avcodec_configuration "<< avcodec_configuration() << std::endl;
//std::cout <<"avcodec_version "<< avcodec_version() << std::endl;
AVFormatContext* pAVFormat = NULL;
//return 0 on success, a negative AVERROR on failure.
const char* pMediaPath = "test_video.mp4";
int iret = avformat_open_input(&pAVFormat, pMediaPath, NULL, NULL);
if (0 == iret) {
std::cout << "avformat_open_input success!" << std::endl;
}
else {
std::cout << "avformat_open_input failed!" << std::endl;
}
//@return >=0 if OK, AVERROR_xxx on error
iret = avformat_find_stream_info(pAVFormat, NULL);
if (0 <= iret) {
std::cout << "avformat_find_stream_info success!" << std::endl;
}
else {
std::cout << "avformat_find_stream_info failed!" << std::endl;
}
av_dump_format(pAVFormat, 0, pMediaPath, 0);
int video_streamid = -1;
int audio_streamid = -1;
const AVCodec* pVideoCodec = NULL;
const AVCodec* pAudioCodec = NULL;
video_streamid = av_find_best_stream(pAVFormat, AVMEDIA_TYPE_VIDEO, -1, -1, &pVideoCodec, 0);
if (AVERROR_STREAM_NOT_FOUND == video_streamid) {
std::cout << "cannot find video stream" << std::endl;
}
audio_streamid = av_find_best_stream(pAVFormat, AVMEDIA_TYPE_AUDIO, -1, -1, &pAudioCodec, 0);
if (AVERROR_STREAM_NOT_FOUND == audio_streamid) {
std::cout << "cannot find audio stream" << std::endl;
}
return 0;
}
其实,还有另外一种方法来获得音视频对应的stream_index。
for (i = 0; i < ifmt_ctx->nb_streams; i++)
{
//Create output AVStream according to input AVStream
AVFormatContext *ofmt_ctx;
AVStream *in_stream = ifmt_ctx->streams[i];
AVStream *out_stream = NULL;
if (ifmt_ctx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO)
{
videoindex = i;
out_stream = avformat_new_stream(ofmt_ctx_v, in_stream->codec->codec);
ofmt_ctx = ofmt_ctx_v;
}
else if (ifmt_ctx->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO)
{
audioindex = i;
out_stream = avformat_new_stream(ofmt_ctx_a, in_stream->codec->codec);
ofmt_ctx = ofmt_ctx_a;
}
else
{
break;
}
}