QT实现视频播放,包含开始、暂停、停止按钮和进度条、总时长、播放进度
时间: 2023-11-08 21:49:19 浏览: 497
实现视频播放的基本思路如下:
1. 使用QMediaPlayer类控制视频的播放和暂停等操作;
2. 使用QVideoWidget类作为视频的显示窗口;
3. 使用QSlider类实现进度条;
4. 使用QLabel类显示总时长和播放进度;
5. 使用QPushButton类实现开始、暂停和停止按钮。
下面是一个简单的示例代码:
```cpp
#include <QMediaPlayer>
#include <QVideoWidget>
#include <QSlider>
#include <QLabel>
#include <QPushButton>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QTime>
class VideoPlayer : public QWidget {
Q_OBJECT
public:
VideoPlayer(QWidget *parent = nullptr) : QWidget(parent) {
// 创建视频播放器
player = new QMediaPlayer(this);
videoWidget = new QVideoWidget(this);
player->setVideoOutput(videoWidget);
// 创建进度条
slider = new QSlider(Qt::Horizontal, this);
slider->setRange(0, 0);
connect(player, &QMediaPlayer::durationChanged, this, &VideoPlayer::setDuration);
connect(player, &QMediaPlayer::positionChanged, this, &VideoPlayer::setPosition);
connect(slider, &QSlider::sliderMoved, this, &VideoPlayer::seek);
// 创建标签
timeLabel = new QLabel("--:-- / --:--", this);
// 创建按钮
playButton = new QPushButton("Play", this);
connect(playButton, &QPushButton::clicked, this, &VideoPlayer::play);
pauseButton = new QPushButton("Pause", this);
connect(pauseButton, &QPushButton::clicked, player, &QMediaPlayer::pause);
stopButton = new QPushButton("Stop", this);
connect(stopButton, &QPushButton::clicked, player, &QMediaPlayer::stop);
// 布局
QHBoxLayout *buttonLayout = new QHBoxLayout;
buttonLayout->addWidget(playButton);
buttonLayout->addWidget(pauseButton);
buttonLayout->addWidget(stopButton);
QHBoxLayout *sliderLayout = new QHBoxLayout;
sliderLayout->addWidget(slider);
sliderLayout->addWidget(timeLabel);
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(videoWidget);
layout->addLayout(sliderLayout);
layout->addLayout(buttonLayout);
setLayout(layout);
}
private slots:
void setDuration(qint64 duration) {
this->duration = duration;
slider->setRange(0, duration);
updateTimeLabel();
}
void setPosition(qint64 position) {
slider->setValue(position);
updateTimeLabel();
}
void seek(int position) {
player->setPosition(position);
updateTimeLabel();
}
void play() {
player->play();
playButton->setEnabled(false);
}
void updateTimeLabel() {
QTime durationTime(0, (duration / 60000) % 60, (duration / 1000) % 60);
QTime positionTime(0, (slider->value() / 60000) % 60, (slider->value() / 1000) % 60);
timeLabel->setText(positionTime.toString("mm:ss") + " / " + durationTime.toString("mm:ss"));
}
private:
QMediaPlayer *player;
QVideoWidget *videoWidget;
QSlider *slider;
QLabel *timeLabel;
QPushButton *playButton, *pauseButton, *stopButton;
qint64 duration;
};
```
使用方法:
```cpp
VideoPlayer *player = new VideoPlayer;
player->show();
player->player->setMedia(QUrl::fromLocalFile("path/to/video"));
```
其中,`QUrl::fromLocalFile` 方法可以将本地文件路径转换为 URL。你只需要将路径替换成你自己的视频文件路径即可。
阅读全文