在 Qt 中使用 FFmpeg 可以通过以下步骤:
首先需要安装 FFmpeg 库,可以从官网下载并安装。
在 Qt 项目中,需要将 FFmpeg 库链接到项目中。这可以通过在 .pro 文件中添加以下行实现:
LIBS += -lavcodec -lavformat -lavutil
调用 FFmpeg API 来读取和处理音视频数据。例如,可以使用 av_read_frame 函数来读取视频帧,使用 avcodec_decode_audio4 函数解码音频数据。
将解码后的音视频数据传递给 Qt 的多媒体模块进行播放。可以使用 QMediaPlayer 类来播放音频文件,使用 QVideoWidget 类来显示视频内容。
示例代码:
#include <QApplication>
#include <QMediaPlayer>
#include <QVideoWidget>
#include <QDebug>
#include <libavformat/avformat.h>
#include <libavcodec/avcodec.h>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
// 初始化 FFmpeg 库
av_register_all();
AVFormatContext *fmt_ctx = NULL;
if (avformat_open_input(&fmt_ctx, "test.mp4", NULL, NULL) != 0) {
qWarning() << "Error opening file";
return -1;
}
if (avformat_find_stream_info(fmt_ctx, NULL) < 0) {
qWarning() << "Error finding stream info";
avformat_close_input(&fmt_ctx);
return -1;
}
int video_stream_index = -1;
for (int i = 0; i < fmt_ctx->nb_streams; i++) {
if (fmt_ctx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
video_stream_index = i;
break;
}
}
if (video_stream_index == -1) {
qWarning() << "No video stream found";
avformat_close_input(&fmt_ctx);
return -1;
}
AVCodecParameters *codec_params = fmt_ctx->streams[video_stream_index]->codecpar;
AVCodec *codec = avcodec_find_decoder(codec_params->codec_id);
if (!codec) {
qWarning() << "Failed to find codec";
avformat_close_input(&fmt_ctx);
return -1;
}
AVCodecContext *codec_ctx = avcodec_alloc_context3(codec);
if (!codec_ctx) {
qWarning() << "Failed to allocate codec context";
avformat_close_input(&fmt_ctx);
return -1;
}
if (avcodec_parameters_to_context(codec_ctx, codec_params) < 0) {
qWarning() << "Failed to copy codec parameters to context";
avcodec_free_context(&codec_ctx);
avformat_close_input(&fmt_ctx);
return -1;
}
if (avcodec_open2(codec_ctx, codec, NULL) < 0) {
qWarning() << "Failed to open codec";
avcodec_free_context(&codec_ctx);
avformat_close_input(&fmt_ctx);
return -1;
}
QMediaPlayer player;
QVideoWidget *widget = new QVideoWidget();
player.setVideoOutput(widget);
widget->show();
AVPacket pkt;
while (av_read_frame(fmt_ctx, &pkt) == 0) {
if (pkt.stream_index != video_stream_index)
continue;
AVFrame *frame = av_frame_alloc();
int frame_finished;
if (avcodec_decode_video2(codec_ctx, frame, &frame_finished, &pkt) < 0) {
qWarning() << "Error decoding video";
av_frame_free(&frame);
continue;
}
if (frame_finished) {
QImage image(frame->data[0], codec_ctx->width, codec_ctx->height, QImage::Format_RGB888);
player.setMedia(QMediaContent(), &image);
}
av_frame_free(&frame);
}
// 清理资源
avcodec_close(codec_ctx);
avcodec_free_context(&codec_ctx);
avformat_close_input(&fmt_ctx);
return a.exec();
}