以下是一个使用FFmpeg开发播放器的简单示例:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
extern "C" {
#include <libavformat/avformat.h>
}
int main(int argc, char *argv[]) {
if (argc < 2) {
printf("Usage: %s [input_file]\n", argv[0]);
return -1;
}
const char *inputFile = argv[1];
av_register_all();
AVFormatContext *formatContext = NULL;
// 打开输入文件
if (avformat_open_input(&formatContext, inputFile, NULL, NULL) != 0) {
printf("Failed to open input file\n");
return -1;
}
// 检索流信息
if (avformat_find_stream_info(formatContext, NULL) < 0) {
printf("Failed to retrieve stream information\n");
return -1;
}
int videoStreamIndex = -1;
// 查找视频流
for (int i = 0; i < formatContext->nb_streams; i++) {
if (formatContext->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
videoStreamIndex = i;
break;
}
}
if (videoStreamIndex == -1) {
printf("No video stream found in the input file\n");
return -1;
}
AVCodecParameters *codecParameters = formatContext->streams[videoStreamIndex]->codecpar;
AVCodec *codec = avcodec_find_decoder(codecParameters->codec_id);
if (!codec) {
printf("Unsupported codec\n");
return -1;
}
AVCodecContext *codecContext = avcodec_alloc_context3(codec);
if (!codecContext) {
printf("Failed to allocate codec context\n");
return -1;
}
// 将流参数拷贝到解码器上下文
if (avcodec_parameters_to_context(codecContext, codecParameters) < 0) {
printf("Failed to copy codec parameters to codec context\n");
return -1;
}
// 打开解码器
if (avcodec_open2(codecContext, codec, NULL) < 0) {
printf("Failed to open codec\n");
return -1;
}
AVPacket packet;
av_init_packet(&packet);
AVFrame *frame = av_frame_alloc();
while (av_read_frame(formatContext, &packet) >= 0) {
if (packet.stream_index == videoStreamIndex) {
// 解码视频帧
int response = avcodec_send_packet(codecContext, &packet);
if (response < 0 || response == AVERROR(EAGAIN)) {
continue;
}
while (response >= 0) {
response = avcodec_receive_frame(codecContext, frame);
if (response == AVERROR(EAGAIN) || response == AVERROR_EOF)
break;
// 在这里可以处理视频帧,例如渲染到屏幕上
}
}
av_packet_unref(&packet);
}
av_frame_free(&frame);
avcodec_close(codecContext);
avformat_close_input(&formatContext);
return 0;
}
请注意,这只是一个简单的示例,仅包含了基本的打开文件、查找视频流、解码和处理视频帧的功能。实际的播放器开发可能需要更多的功能和错误处理。你可以根据自己的需求进行扩展和修改。
内容由零声教学AI助手提供,问题来源于学员提问