qmediaplayer是QT5的播放视频的一个模块。它在很多时候还是要基于第三方的解码器。这里以Ubuntu系统为例,记录其用法及进度条qslider的控制。
首先,制作一个简单的界面文件mainwindow.ui:
然后,下载一个mp4或其他格式视频(比如mkv),基于以上UI进行播放控制操作。
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
timer = new QTimer();
ui->setupUi(this);
player = new QMediaPlayer;
list = new QMediaPlaylist(player);
//list->addMedia(QUrl::fromLocalFile("/home/m30.mp4"));
//list->addMedia(QUrl::fromLocalFile("/home/share/2023.mkv"));
list->addMedia(QUrl::fromLocalFile("/home/share/50.mp4"));
list->setCurrentIndex(0);
list->setPlaybackMode(QMediaPlaylist::Loop);
player->setPlaylist(list);
ui->widget->setAspectRatioMode(Qt::IgnoreAspectRatio);
long time = player->duration();
printf("duration: %lld\n", player->duration());
player->setVideoOutput(ui->widget);
timer->setInterval(5000);
connect(timer, SIGNAL(timeout()), this, SLOT(onTimeout()));
timer->start();
ui->horizontalSlider->setValue(0);
connect(player, &QMediaPlayer::durationChanged, ui->horizontalSlider, &QSlider::setMaximum);
connect(player, &QMediaPlayer::positionChanged, ui->horizontalSlider, &QSlider::setValue);
connect(ui->horizontalSlider, &QSlider::sliderMoved, this, [this](int value){
printf("slide: %d\n", value);
player->setPosition(value);
});
player->setVolume(100);
player->play();
//player->setPosition();
}
void MainWindow::onTimeout()
{
printf("timeout\n");
player->setPosition(30*1000);
}
MainWindow::~MainWindow()
{
delete ui;
player->stop();
if (player)
delete player;
if(list)
delete list;
}
代码集成了两种控制方式:1.定时5秒循环让进度跳到某个30秒位置;2.手动拖动进度条控制播放进度。
友好期间,顺道贴上mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QMediaPlayer>
#include <QVideoWidget>
#include <QMediaPlaylist>
#include <QTimer>
#include <QSlider>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private:
Ui::MainWindow *ui;
QMediaPlayer *player;
QVideoWidget * videoWidget;
QMediaPlaylist * list;
QTimer* timer;
QSlider* slid;
public slots:
void onTimeout();
};
#endif // MAINWINDOW_H