一. 需求
利用Qt自带的媒体模块,播放mp4等媒体文件。
二. 实现
- pro文件修改
QT += core gui multimedia multimediawidgets
- ui中放一个QWidget,并提升为QVideoWidget.
- widget.h 文件。
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QMediaPlayer>
#include <QVideoWidget>
#include <QMediaPlaylist>
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
private slots:
void on_fileBtn_clicked();
private:
Ui::Widget *ui;
QMediaPlayer* mediaPlayer;
QMediaPlaylist* mediaPlayList;
};
#endif // WIDGET_H
- widget.cpp 文件
#include "widget.h"
#include "ui_widget.h"
#include <QFileDialog>
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
mediaPlayer = new QMediaPlayer(this);
mediaPlayList = new QMediaPlaylist(mediaPlayer);
mediaPlayer->setVideoOutput(ui->widget);
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_fileBtn_clicked()
{
QString file = QFileDialog::getOpenFileName(this,"open file",".","*.*");
if(file.isEmpty())
return;
mediaPlayList->clear();
mediaPlayList->addMedia(QUrl::fromLocalFile(file));
mediaPlayList->setCurrentIndex(0);
mediaPlayer->setPlaylist(mediaPlayList);
mediaPlayer->play();
}
- 涉及到媒体,就涉及到编解码,所以就需要安装编解码器,直接安装这个即可:
https://www.codecguide.com/download_kl.htm
不然会出现如下错误: DirectShowPlayerService::doRender: Unresolved error code 0x80040266
三. 效果