Qt5中通过FFmpeg拉流实现视频播放(简单的在Qt中使用FFmpeg的demo,没有做任何优化)
本地环境:
Qt5.15.2 + MSVC2019_64bit编译器
- 新建Qt项目,项目工程结构

ffmpeg头文件路径:
ffmpeg库路径:
exe输出文件夹,需要ffmpeg的dll库加进来:
- 在项目pro文件中添加ffmpeg头文件和库链接:
QT += core gui concurrent
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
# 输出目录
DESTDIR = $${
OUT_PWD}/../output
TARGET = FFmpegDemo
CONFIG += c++17
# You can make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
SOURCES += \
main.cpp \
mainwindow.cpp
HEADERS += \
mainwindow.h
FORMS += \
mainwindow.ui
# ffmpeg头文件
INCLUDEPATH += $$PWD/../3rdparty/ffmpeg/include
# ffmpeg库链接
LIBS += -L$$PWD/../3rdparty/ffmpeg/lib -lavformat -lavfilter -lavcodec -lswresample -lswscale -lavutil
# Default rules for deployment.
qnx: target.path = /tmp/$${
TARGET}/bin
else: unix:!android: target.path = /opt/$${
TARGET}/bin
!isEmpty(target.path): INSTALLS += target
- 在Mainwindow.ui中加入一个QLabel控件即可。
- 在Mainwindow.h中添加ffmpeg头文件
//当前C++兼容C语言
extern "C"
{
//avcodec:编解码(最重要的库)
#include <libavcodec/avcodec.h>
//avformat:封装格式处理
#include <libavformat/avformat.h>
//swscale:视频像素数据格式转换
#include <libswscale/swscale.h>
//avdevice:各种设备的输入输出
#include <libavdevice/avdevice.h>
//avutil:工具库(大部分库都需要这个库的支持)
#include <libavutil/avutil.h>
#include <libavutil/imgutils.h>
#include <libavutil/time.h>
}
- 在Mainwindow.cpp中调用ffmpeg接口,实现对url地址的拉流播放
void MainWindow::transVideoToImage(const QString &url)
{
//avdevice_register_all(); //硬件设备注册
avformat_network_init(); //网络注册
//创建封装格式上下文
AVFormatContext *formatContext = avformat_alloc_context();
//打开本地文件到封装格式上下文中。
QString filename = url;
int avformat_open_ret = avformat_open_input(&formatContext, filename.toLatin1(), NULL, NULL);
if(avformat_open_ret < 0)
{
char *result = new char[64];
av_strerror(avformat_open_ret,result,64);
qDebug() << QString(u8"错误信息:%1").arg(result);
}
qDebug() << u8"打开多媒体文件成功!";
//在封装格式上下文中获取音视频流信息
int avformat_find_ret = avformat_find_stream_info(formatContext, NULL);
if(avformat_find_ret < 0)
{
char *result = new char[64];
av_strerror(avformat_open_ret,result,64

最低0.47元/天 解锁文章
961





