中文字幕av专区_日韩电影在线播放_精品国产精品久久一区免费式_av在线免费观看网站

溫馨提示×

Qt5+QMediaPlayer實現音樂播放器的示例代碼

Qt5
小云
138
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
吴忠市| 丹凤县| 合作市| 澄城县| 临海市| 安吉县| 定兴县| 沁源县| 威信县| 前郭尔| 福泉市| 临海市| 纳雍县| 额济纳旗| 临漳县| 灵宝市| 三门县| 宣恩县| 西安市| 河曲县| 固安县| 嘉兴市| 当涂县| 东平县| 上饶县| 安宁市| 崇左市| 屯昌县| 喀什市| 凤翔县| 治多县| 资阳市| 日土县| 邹城市| 广饶县| 黔南| 平南县| 樟树市| 柳林县| 景洪市| 平和县|