ffmpeg-读取媒体文件信息-avformat_open_input

实例代码

Code
int video_audio_info(int argc, char *argv[])
{
	if (argc < 2) {
		printf("Usage : %s mediaFile\n", argv[0]);
		return -1;
	}
	AVFormatContext *ic = NULL;
	char path[20] = { 0 };
	strcpy(path, argv[1]);
	// 1.打开媒体文件
	int ret = avformat_open_input(&ic, path, 0, 0);
	if (ret != 0)
	{
		printf("avformat_open_input called failed:");
		return -1;
	}
	printf("avformat_open_input called success\n");
	// 2.获取流信息
	// 获取媒体文件总时长,单位为毫秒,和流的数量
	printf("before duration :%ld, nb_stream :%d\n", ic->duration, ic->nb_streams);
	if (avformat_find_stream_info(ic, 0) >= 0) {
		printf("after duration :%ld, nb_stream :%d\n", ic->duration, ic->nb_streams);
	}
	// 3.查看视频流
	int fps = 0;
	int videoStream = 0;
	int audioStream = 1;
	for (int i = 0; i < ic->nb_streams; i++) {
		AVStream *as = ic->streams[i];
		// av_find_best_stream(AVFormatContext * ic, enum AVMediaType type, int wanted_stream_nb, 
			// int related_stream, const struct AVCodec * * decoder_ret, int flags)
		if (as->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
		///// videoStream = av_find_best_stream(ic, AVMEDIA_TYPE_VIDEO, -1, -1, NULL, 0);
			printf("video stream.................\n");
			videoStream = i;
			//fps = (int)_r2d(as->avg_frame_rate);
			printf("width = %d, height = %d, codecid = %d, format = %d, fps = %d\n",
				as->codecpar->width,  	//视频宽度
				as->codecpar->height, 	//视频高度
				as->codecpar->codec_id,	//视频的编解码ID
				as->codecpar->format,	//视频像素格式:AVPixelFormat
				as->avg_frame_rate.num);	//帧率
		}
		// 4.查看音频流
		// audioStream = av_find_best_stream(ic, AVMEDIA_TYPE_AUDIO, -1, -1, NULL, 0);
		else if (as->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
			printf("audio stream.................\n");
			audioStream = i;
			printf("sample_rate = %d, channels = %d, sample_format = %d\n",
				 as->codecpar->sample_rate,	//音频采样率
				 as->codecpar->channels,	//音频声道数
				 as->codecpar->format);		//音频采样格式:AVSampleFormat
		}
	}
	// 5.关闭并释放资源
	avformat_close_input(&ic);
	return 0;
}

结果

posted @ 2024-01-28 20:55  starc再起航  阅读(7)  评论(0编辑  收藏  举报