Qt使用FFmpeg播放视频

这篇具有很好参考价值的文章主要介绍了Qt使用FFmpeg播放视频。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

一、使用场景

  因为项目中需要加载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.源文件:文章来源地址https://www.toymoban.com/news/detail-729889.html

#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();
}

到了这里,关于Qt使用FFmpeg播放视频的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • qt+ffmpeg 实现音视频播放(二)之音频播放

    通过  avformat_open_input () 打开媒体文件并分配和初始化  AVFormatContext   结构体。 函数原型如下: int avformat_open_input(AVFormatContext **ps, const char *url, AVInputFormat *fmt, AVDictionary **options); 参数说明: - `ps`:指向 `AVFormatContext` 结构体指针的指针,用于存储打开的媒体文件的信息。

    2024年04月22日
    浏览(40)
  • FFMpeg-3、基于QT实现音视频播放显示

    1、音视频播放的基础知识 内容来自雷神博客 1、在Windows平台下的视频播放技术主要有以下三种:GDI,Direct3D和OpenGL;音频播放技术主要是DirectSound。 SDL本身并不具有播放显示的功能,它只是封装了底层播放显示的代码 记录三种视频显示技术:GDI,Direct3D,OpenGL。其中Direct3D包

    2024年02月03日
    浏览(47)
  • 【Qt+FFmpeg】鼠标滚轮放大、缩小、移动——解码播放本地视频(三)

     上一期我们实现了播放、暂停、重播、倍速功能,这期来谈谈如何实现鼠标滚轮放大缩小和移动;如果还没看过上期,请移步 【Qt+FFmpeg】解码播放本地视频(一)_logani的博客-CSDN博客【Qt+FFmpeg】解码播放本地视频(二)——实现播放、暂停、重播、倍速功能_logani的博客-C

    2024年02月10日
    浏览(29)
  • Qt基于FFmpeg解码本地视频生成H264文件并播放

    用eseye_u.exe 打开H264文件并播放 本文福利, 免费领取C++音视频学习资料包、技术视频 ,内容包括(音视频开发,面试题, FFmpeg , webRTC , rtmp , hls , rtsp , ffplay , srs ) ↓↓↓↓↓↓ 见下面↓↓文章底部点击免费领取↓↓   三、核心代码:  main中创建对象即可测试:

    2023年04月17日
    浏览(29)
  • QT软件开发-基于FFMPEG设计视频播放器-软解图像(一)

    QT软件开发-基于FFMPEG设计视频播放器-CPU软解视频(一) https://xiaolong.blog.csdn.net/article/details/126832537 QT软件开发-基于FFMPEG设计视频播放器-GPU硬解视频(二) https://xiaolong.blog.csdn.net/article/details/126833434 QT软件开发-基于FFMPEG设计视频播放器-解码音频(三) https://xiaolong.blog.csdn.

    2023年04月08日
    浏览(32)
  • Qt/C++视频监控安卓版/多通道显示视频画面/录像存储/视频播放安卓版/ffmpeg安卓

    随着监控行业的发展,越来越多的用户场景是需要在手机上查看监控,而之前主要的监控系统都是在PC端,毕竟PC端屏幕大,能够看到的画面多,解码性能也强劲。早期的手机估计性能弱鸡,而现在的手机性能不是一般的牛,甚至超越了PC机的性能,所以手机上查看多路监控也

    2024年02月03日
    浏览(36)
  • QtAV:基于Qt和FFmpeg的跨平台高性能音视频播放框架

    目录 一.简介 1.特性 2.支持的平台 3.简单易用的接口 二.编译 1.下载依赖包 2.开始编译 2.1克隆 2.2修改配置文件 2.3编译 三.试用 官网地址:http://www.qtav.org/ Github地址:https://github.com/wang-bin/QtAV ●支持大部分播放功能 ●播放、暂停、播放速度、快进快退、字幕、音量、声道、音

    2024年01月22日
    浏览(51)
  • 用Qt开发的ffmpeg流媒体播放器,支持截图、录像,支持音视频播放,支持本地文件播放、网络流播放

    本工程qt用的版本是5.8-32位,ffmpeg用的版本是较新的5.1版本。它支持TCP或UDP方式拉取实时流,实时流我采用的是监控摄像头的RTSP流。音频播放采用的是QAudioOutput,视频经ffmpeg解码并由YUV转RGB后是在QOpenGLWidget下进行渲染显示。本工程的代码有注释,可以通过本博客查看代码或者

    2024年02月03日
    浏览(75)
  • linux+QT+FFmpeg 6.0,把多个QImage组合成一个视频

    我这里是专门搞了个类封装,我把这个类当成线程使用了,在启动程序的时候直接当线程启动recordInit():比如这样  然后我在需要合成视频的时候先调用初始化: 再传入QImage: 这样就不会造成卡死主线程的情况 我在使用FFmpeg的时候主要出现两个比较明显的情况: 1.pix_fmt为-1的情况

    2024年02月11日
    浏览(29)
  • Qt编写全能播放组件(支持ffmpeg2/3/4/5/6/Qt4/5/6)

    从代码层面以及自由度来说,用ffmpeg来写全能播放组件是最佳方案(跨平台最好最多、编解码能力最强),尽管已经有优秀的vlc/mpv等方案可以直接用,但是vlc/mpv对标主要是播放器应用层面,其他层面比如视频监控行业领域就比较鸡肋,所以还是从底层一点一滴做解码编码会

    2024年02月08日
    浏览(30)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包