Qt使用FFmpeg播放视频
liuian 2025-01-18 21:55 18 浏览
一、使用场景
因为项目中需要加载MP4播放开机视频,而我们的设备所使用的架构为arm架构,其中缺乏一些多媒体库。安装这些插件库比较麻烦,所以最终决定使用FFmpeg播放视频。
二、下载编译ffmpeg库
2.1 下载源码
源码下载路径:https://www.ffmpeg.org/download.html#build-windows
2.2 编译源码
1) 解压:将源码放到指定目录,并运行"tar -jxvf ffmpeg-snapshot.tar.bz2"。若是xxx.tar.gz源文件,则用"tar -zxvf ffmpeg-xxx.tar.gz"。
2) 创建构建目录,"cd ffmpeg", "mkdir build";
3)编译:
a) ubuntu编译: "./configure --enable-static --prefix=./build"
b)arm交叉编译: "./configure --cc=xxx/aarch64-linux-gnu-gcc(QT指定的gcc路径) --cxx=xxx/aarch64-linux-gnu-g++ --enable-staticc(QT指定的g++路径) --prefix=./build --enable-cross-compile --arch=arm64 --target-os=linux"。
4) make安装: "make && make install"。
5) 运行:若需要运行ffmpeg则需要增加--enable-shared参数,并且添加环境变量"export LD_LIBRARY_PATH=xxx/build/lib/"。
6)使用帮助: 在xxx/build/bin路径下运行"./ffmpeg --help"。
2.3 常见报错
1) 交叉编译需要指定对应的gcc和g++编译器和其它的如平台参数,Linux的QTCreator可以通过如下选项查看对应的编译器路径,工程-》管理构建-》编译器-》指南(Manual)-》双击gcc或g++。注意在操作之前需要先选择工程当前的运行和构建平台为arrch64。
2) make install 报错:"strip: Unable to recognise the format of the input file":将config.mak中的"Trip=strip"改为"Trip=arm -linux-strip"。
三、使用源码
1.在工程中导入头文件和库,注意库顺序。eg:
INCLUDEPATH += xxx/build/include
LIBS += -Lxxx/xxx -lavformat\
-lavdevice \
-lavcodec \
-lswresample \
-lavfilter \
-lavutil \
-lswscale
2.头文件
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QDebug>
#include <QTimer>
#include <QTime>
#include <QAudioOutput>
extern "C"
{
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libswscale/swscale.h>
#include <libavdevice/avdevice.h>
#include <libavformat/version.h>
#include <libavutil/time.h>
#include <libavutil/mathematics.h>
#include <libavfilter/buffersink.h>
#include <libavfilter/buffersrc.h>
#include <libavutil/avutil.h>
#include <libavutil/imgutils.h>
#include <libavutil/pixfmt.h>
#include <libswresample/swresample.h>
}
#define MAX_AUDIO_FRAME_SIZE 192000
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
public slots:
void timeCallback(void);
void on_play_clicked();
void resizeEvent(QResizeEvent* );
private:
Ui::MainWindow *ui;
int playVedio(void);
QTimer *timer; // 定时播放,根据帧率来
int vedioW,vedioH; // 图像宽高
QList<QPixmap> vedioBuff; // 图像缓存区
QString myUrl = QString("E:/workspace/Qt_workspace/ffmpeg/三国之战神无双.mp4"); // 视频地址
AVFormatContext *pFormatCtx;
AVCodecContext *pCodecCtx;
AVCodec *pCodec;
AVFrame *pFrame, *pFrameRGB;
int ret, got_picture,got_audio; // 视频解码标志
int videoindex; // 视频序号
// 音频
int audioindex; // 音频序号
AVCodecParameters *aCodecParameters;
AVCodec *aCodec;
AVCodecContext *aCodecCtx;
QByteArray byteBuf;//音频缓冲
QAudioOutput *audioOutput;
QIODevice *streamOut;
};
#endif // MAINWINDOW_H
3.源文件:
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
// qDebug(avcodec_configuration());
// unsigned version = avcodec_version();
// QString ch = QString::number(version,10);
// qDebug()<<"version:"<<version;
timer = new QTimer(this);
timer->setTimerType(Qt::PreciseTimer); // 精准定时设置
connect(timer,SIGNAL(timeout()),this,SLOT(timeCallback()));
}
void MainWindow::timeCallback(void)
{
// 视频缓存播放
if(!vedioBuff.isEmpty())
{
ui->label->setPixmap(vedioBuff.at(0));
vedioBuff.removeAt(0);
}
else {
timer->stop();
}
// 音频缓存播放
if(audioOutput && audioOutput->state() != QAudio::StoppedState && audioOutput->state() != QAudio::SuspendedState)
{
int writeBytes = qMin(byteBuf.length(), audioOutput->bytesFree());
streamOut->write(byteBuf.data(), writeBytes);
byteBuf = byteBuf.right(byteBuf.length() - writeBytes);
}
}
void Delay_MSec(unsigned int msec)
{
QTime _Timer = QTime::currentTime().addMSecs(msec);
while( QTime::currentTime() < _Timer )
QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
}
int MainWindow::playVedio(void)
{
QAudioFormat fmt;
fmt.setSampleRate(44100);
fmt.setSampleSize(16);
fmt.setChannelCount(2);
fmt.setCodec("audio/pcm");
fmt.setByteOrder(QAudioFormat::LittleEndian);
fmt.setSampleType(QAudioFormat::SignedInt);
audioOutput = new QAudioOutput(fmt);
streamOut = audioOutput->start();
char *filepath = myUrl.toUtf8().data();
av_register_all();
avformat_network_init();
pFormatCtx = avformat_alloc_context();
// 打开视频文件,初始化pFormatCtx结构
if(avformat_open_input(&pFormatCtx,filepath,NULL,NULL)!=0){
qDebug("视频文件打开失败.\n");
return -1;
}
// 获取音视频流
if(avformat_find_stream_info(pFormatCtx,NULL)<0){
qDebug("媒体流获取失败.\n");
return -1;
}
videoindex = -1;
audioindex = -1;
//nb_streams视音频流的个数,这里当查找到视频流时就中断了。
for(int i=0; i<pFormatCtx->nb_streams; i++)
if(pFormatCtx->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO){
videoindex=i;
break;
}
if(videoindex==-1){
qDebug("找不到视频流.\n");
return -1;
}
//nb_streams视音频流的个数,这里当查找到音频流时就中断了。
for(int i=0; i<pFormatCtx->nb_streams; i++)
if(pFormatCtx->streams[i]->codecpar->codec_type==AVMEDIA_TYPE_AUDIO){
audioindex=i;
break;
}
if(audioindex==-1){
qDebug("找不到音频流.\n");
return -1;
}
//获取视频流编码结构
pCodecCtx=pFormatCtx->streams[videoindex]->codec;
float frameNum = pCodecCtx->framerate.num; // 每秒帧数
if(frameNum>100) frameNum = frameNum/1001;
int frameRate = 1000/frameNum; //
qDebug("帧/秒 = %f 播放间隔是时间=%d\n",frameNum,frameRate);
//查找解码器
pCodec=avcodec_find_decoder(pCodecCtx->codec_id);
if(pCodec==NULL)
{
qDebug("找不到解码器.\n");
return -1;
}
//使用解码器读取pCodecCtx结构
if(avcodec_open2(pCodecCtx, pCodec,NULL)<0)
{
qDebug("打开视频码流失败.\n");
return -1;
}
//获取音频流编码结构-------------------------------------------------------------
aCodecParameters = pFormatCtx->streams[audioindex]->codecpar;
aCodec = avcodec_find_decoder(aCodecParameters->codec_id);
if (aCodec == 0) {
qDebug("找不到解码器.\n");
return -1;
}
aCodecCtx = avcodec_alloc_context3(aCodec);
avcodec_parameters_to_context(aCodecCtx, aCodecParameters);
//使用解码器读取aCodecCtx结构
if (avcodec_open2(aCodecCtx, aCodec, 0) < 0) {
qDebug("打开视频码流失败.\n");
return 0;
}
// 清空缓存区
byteBuf.clear();
vedioBuff.clear();
//创建帧结构,此函数仅分配基本结构空间,图像数据空间需通过av_malloc分配
pFrame = av_frame_alloc();
pFrameRGB = av_frame_alloc();
// 获取音频参数
uint64_t out_channel_layout = aCodecCtx->channel_layout;
AVSampleFormat out_sample_fmt = AV_SAMPLE_FMT_S16;
int out_sample_rate = aCodecCtx->sample_rate;
int out_channels = av_get_channel_layout_nb_channels(out_channel_layout);
uint8_t *audio_out_buffer = (uint8_t *)av_malloc(MAX_AUDIO_FRAME_SIZE*2);
SwrContext *swr_ctx = swr_alloc_set_opts(NULL, out_channel_layout, out_sample_fmt,out_sample_rate, aCodecCtx->channel_layout, aCodecCtx->sample_fmt, aCodecCtx->sample_rate, 0, 0);
swr_init(swr_ctx);
//创建动态内存,创建存储图像数据的空间
unsigned char *out_buffer = (unsigned char *)av_malloc(av_image_get_buffer_size(AV_PIX_FMT_RGB32, pCodecCtx->width, pCodecCtx->height, 1));
av_image_fill_arrays(pFrameRGB->data, pFrameRGB->linesize, out_buffer, AV_PIX_FMT_RGB32, pCodecCtx->width, pCodecCtx->height, 1);
AVPacket *packet = (AVPacket *)av_malloc(sizeof(AVPacket));
//初始化img_convert_ctx结构
struct SwsContext *img_convert_ctx = sws_getContext(pCodecCtx->width, pCodecCtx->height, pCodecCtx->pix_fmt, pCodecCtx->width, pCodecCtx->height, AV_PIX_FMT_RGB32, SWS_BICUBIC, NULL, NULL, NULL);
timer->start(frameRate); //定时间隔播放
while (av_read_frame(pFormatCtx, packet) >= 0){
if (packet->stream_index == audioindex){
int ret = avcodec_decode_audio4(aCodecCtx, pFrame, &got_audio, packet);
if ( ret < 0)
{
qDebug("解码失败.\n");
return 0;
}
if (got_audio)
{
int len = swr_convert(swr_ctx, &audio_out_buffer, MAX_AUDIO_FRAME_SIZE, (const uint8_t **)pFrame->data, pFrame->nb_samples);
if (len <= 0)
{
continue;
}
int dst_bufsize = av_samples_get_buffer_size(0, out_channels, len, out_sample_fmt, 1);
QByteArray atemp = QByteArray((const char *)audio_out_buffer, dst_bufsize);
byteBuf.append(atemp);
}
}
//如果是视频数据
else if (packet->stream_index == videoindex){
//解码一帧视频数据
ret = avcodec_decode_video2(pCodecCtx, pFrame, &got_picture, packet);
if (ret < 0){
qDebug("解码失败.\n");
return 0;
}
if (got_picture){
sws_scale(img_convert_ctx, (const unsigned char* const*)pFrame->data, pFrame->linesize, 0, pCodecCtx->height,
pFrameRGB->data, pFrameRGB->linesize);
QImage img((uchar*)pFrameRGB->data[0],pCodecCtx->width,pCodecCtx->height,QImage::Format_RGB32);
img = img.scaled(vedioW, vedioH);
QPixmap temp = QPixmap::fromImage(img);
vedioBuff.append(temp);
Delay_MSec(frameRate-5); // 这里需要流出时间来显示,如果不要这个延时界面回卡死到整个视频解码完成才能播放显示
//ui->label->setPixmap(temp);
}
}
av_free_packet(packet);
}
sws_freeContext(img_convert_ctx);
av_frame_free(&pFrameRGB);
av_frame_free(&pFrame);
avcodec_close(pCodecCtx);
avformat_close_input(&pFormatCtx);
}
void MainWindow::resizeEvent(QResizeEvent* )
{
vedioW = ui->label->width();
vedioH = ui->label->height();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_play_clicked()
{
vedioW = ui->label->width();
vedioH = ui->label->height();
if(timer->isActive()) timer->stop();
playVedio();
}
相关推荐
- 总结下SpringData JPA 的常用语法
-
SpringDataJPA常用有两种写法,一个是用Jpa自带方法进行CRUD,适合简单查询场景、例如查询全部数据、根据某个字段查询,根据某字段排序等等。另一种是使用注解方式,@Query、@Modi...
- 解决JPA在多线程中事务无法生效的问题
-
在使用SpringBoot2.x和JPA的过程中,如果在多线程环境下发现查询方法(如@Query或findAll)以及事务(如@Transactional)无法生效,通常是由于S...
- PostgreSQL系列(一):数据类型和基本类型转换
-
自从厂子里出来后,数据库的主力就从Oracle变成MySQL了。有一说一哈,贵确实是有贵的道理,不是开源能比的。后面的工作里面基本上就是主MySQL,辅MongoDB、ES等NoSQL。最近想写一点跟...
- 基于MCP实现text2sql
-
目的:基于MCP实现text2sql能力参考:https://blog.csdn.net/hacker_Lees/article/details/146426392服务端#选用开源的MySQLMCP...
- ORACLE 错误代码及解决办法
-
ORA-00001:违反唯一约束条件(.)错误说明:当在唯一索引所对应的列上键入重复值时,会触发此异常。ORA-00017:请求会话以设置跟踪事件ORA-00018:超出最大会话数ORA-00...
- 从 SQLite 到 DuckDB:查询快 5 倍,存储减少 80%
-
作者丨Trace译者丨明知山策划丨李冬梅Trace从一开始就使用SQLite将所有数据存储在用户设备上。这是一个非常不错的选择——SQLite高度可靠,并且多种编程语言都提供了广泛支持...
- 010:通过 MCP PostgreSQL 安全访问数据
-
项目简介提供对PostgreSQL数据库的只读访问功能。该服务器允许大型语言模型(LLMs)检查数据库的模式结构,并执行只读查询操作。核心功能提供对PostgreSQL数据库的只读访问允许L...
- 发现了一个好用且免费的SQL数据库工具(DBeaver)
-
缘起最近Ai不是大火么,想着自己也弄一些开源的框架来捣腾一下。手上用着Mac,但Mac都没有显卡的,对于学习Ai训练模型不方便,所以最近新购入了一台4090的拯救者,打算用来好好学习一下Ai(呸,以上...
- 微软发布.NET 10首个预览版:JIT编译器再进化、跨平台开发更流畅
-
IT之家2月26日消息,微软.NET团队昨日(2月25日)发布博文,宣布推出.NET10首个预览版更新,重点改进.NETRuntime、SDK、libraries、C#、AS...
- 数据库管理工具Navicat Premium最新版发布啦
-
管理多个数据库要么需要使用多个客户端应用程序,要么找到一个可以容纳你使用的所有数据库的应用程序。其中一个工具是NavicatPremium。它不仅支持大多数主要的数据库管理系统(DBMS),而且它...
- 50+AI新品齐发,微软Build放大招:拥抱Agent胜算几何?
-
北京时间5月20日凌晨,如果你打开微软Build2025开发者大会的直播,最先吸引你的可能不是一场原本属于AI和开发者的技术盛会,而是开场不久后的尴尬一幕:一边是几位微软员工在台下大...
- 揭秘:一条SQL语句的执行过程是怎么样的?
-
数据库系统能够接受SQL语句,并返回数据查询的结果,或者对数据库中的数据进行修改,可以说几乎每个程序员都使用过它。而MySQL又是目前使用最广泛的数据库。所以,解析一下MySQL编译并执行...
- 各家sql工具,都闹过哪些乐子?
-
相信这些sql工具,大家都不陌生吧,它们在业内绝对算得上第一梯队的产品了,但是你知道,他们都闹过什么乐子吗?首先登场的是Navicat,这款强大的数据库管理工具,曾经让一位程序员朋友“火”了一把。Na...
- 详解PG数据库管理工具--pgadmin工具、安装部署及相关功能
-
概述今天主要介绍一下PG数据库管理工具--pgadmin,一起来看看吧~一、介绍pgAdmin4是一款为PostgreSQL设计的可靠和全面的数据库设计和管理软件,它允许连接到特定的数据库,创建表和...
- Enpass for Mac(跨平台密码管理软件)
-
还在寻找密码管理软件吗?密码管理软件有很多,但是综合素质相当优秀且完全免费的密码管理软件却并不常见,EnpassMac版是一款免费跨平台密码管理软件,可以通过这款软件高效安全的保护密码文件,而且可以...
- 一周热门
-
-
Python实现人事自动打卡,再也不会被批评
-
【验证码逆向专栏】vaptcha 手势验证码逆向分析
-
Psutil + Flask + Pyecharts + Bootstrap 开发动态可视化系统监控
-
一个解决支持HTML/CSS/JS网页转PDF(高质量)的终极解决方案
-
再见Swagger UI 国人开源了一款超好用的 API 文档生成框架,真香
-
网页转成pdf文件的经验分享 网页转成pdf文件的经验分享怎么弄
-
C++ std::vector 简介
-
飞牛OS入门安装遇到问题,如何解决?
-
系统C盘清理:微信PC端文件清理,扩大C盘可用空间步骤
-
10款高性能NAS丨双十一必看,轻松搞定虚拟机、Docker、软路由
-
- 最近发表
- 标签列表
-
- python判断字典是否为空 (50)
- crontab每周一执行 (48)
- aes和des区别 (43)
- bash脚本和shell脚本的区别 (35)
- canvas库 (33)
- dataframe筛选满足条件的行 (35)
- gitlab日志 (33)
- lua xpcall (36)
- blob转json (33)
- python判断是否在列表中 (34)
- python html转pdf (36)
- 安装指定版本npm (37)
- idea搜索jar包内容 (33)
- css鼠标悬停出现隐藏的文字 (34)
- linux nacos启动命令 (33)
- gitlab 日志 (36)
- adb pull (37)
- python判断元素在不在列表里 (34)
- python 字典删除元素 (34)
- vscode切换git分支 (35)
- python bytes转16进制 (35)
- grep前后几行 (34)
- hashmap转list (35)
- c++ 字符串查找 (35)
- mysql刷新权限 (34)