以下是一個使用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"
這個示例代碼創建了一個簡單的音樂播放器界面,包含打開文件按鈕、播放按鈕、暫停按鈕、停止按鈕和一個進度條。通過點擊打開按鈕選擇音樂文件,然后點擊播放按鈕開始播放音樂,點擊暫停按鈕暫停音樂,點擊停止按鈕停止音樂。進度條可以用來控制音樂的播放位置。