Qt5

Qt5+QMediaPlayer实现音乐播放器的示例代码

小云
110
2023-08-11 13:00:44
栏目: 编程语言

以下是一个使用Qt5和QMediaPlayer实现音乐播放器的示例代码:

#include <QtWidgets>
#include <QMediaPlayer>
class MusicPlayer : public QWidget
{
Q_OBJECT
public:
MusicPlayer(QWidget *parent = nullptr);
private slots:
void openFile();
void play();
void stop();
void pause();
void updateDuration(qint64 duration);
void updatePosition(qint64 position);
private:
QPushButton *m_openButton;
QPushButton *m_playButton;
QPushButton *m_pauseButton;
QPushButton *m_stopButton;
QSlider *m_positionSlider;
QMediaPlayer *m_player;
};
MusicPlayer::MusicPlayer(QWidget *parent)
: QWidget(parent)
{
m_openButton = new QPushButton("Open");
connect(m_openButton, &QPushButton::clicked, this, &MusicPlayer::openFile);
m_playButton = new QPushButton("Play");
connect(m_playButton, &QPushButton::clicked, this, &MusicPlayer::play);
m_pauseButton = new QPushButton("Pause");
connect(m_pauseButton, &QPushButton::clicked, this, &MusicPlayer::pause);
m_stopButton = new QPushButton("Stop");
connect(m_stopButton, &QPushButton::clicked, this, &MusicPlayer::stop);
m_positionSlider = new QSlider(Qt::Horizontal);
connect(m_positionSlider, &QSlider::sliderMoved, m_player, &QMediaPlayer::setPosition);
m_player = new QMediaPlayer;
connect(m_player, &QMediaPlayer::durationChanged, this, &MusicPlayer::updateDuration);
connect(m_player, &QMediaPlayer::positionChanged, this, &MusicPlayer::updatePosition);
QHBoxLayout *layout = new QHBoxLayout;
layout->addWidget(m_openButton);
layout->addWidget(m_playButton);
layout->addWidget(m_pauseButton);
layout->addWidget(m_stopButton);
QVBoxLayout *mainLayout = new QVBoxLayout;
mainLayout->addLayout(layout);
mainLayout->addWidget(m_positionSlider);
setLayout(mainLayout);
}
void MusicPlayer::openFile()
{
QString filePath = QFileDialog::getOpenFileName(this, "Open File");
if (!filePath.isEmpty())
{
m_player->setMedia(QUrl::fromLocalFile(filePath));
m_player->setVolume(50);
}
}
void MusicPlayer::play()
{
m_player->play();
}
void MusicPlayer::stop()
{
m_player->stop();
}
void MusicPlayer::pause()
{
m_player->pause();
}
void MusicPlayer::updateDuration(qint64 duration)
{
m_positionSlider->setRange(0, duration);
}
void MusicPlayer::updatePosition(qint64 position)
{
m_positionSlider->setValue(position);
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
MusicPlayer player;
player.show();
return app.exec();
}
#include "main.moc"

这个示例代码创建了一个简单的音乐播放器界面,包含打开文件按钮、播放按钮、暂停按钮、停止按钮和一个进度条。通过点击打开按钮选择音乐文件,然后点击播放按钮开始播放音乐,点击暂停按钮暂停音乐,点击停止按钮停止音乐。进度条可以用来控制音乐的播放位置。

0
看了该问题的人还看了