主界面
点击play按钮播放或暂停音乐,拖动进度条,音乐对应播放。
QWidget window;
QPushButton* playButton = new QPushButton("Play");
// Qt 播放音乐
// 创建 QMediaPlayer 对象
QMediaPlayer* player = new QMediaPlayer;
// 指定音频文件的路径
QString audioFilePath = QString::fromLocal8Bit(std::string("./红昭愿.mp3").c_str());
// 加载音频文件
player->setMedia(QUrl::fromLocalFile(audioFilePath));
// 创建进度条
QSlider* seekSlider = new QSlider(Qt::Horizontal);
QObject::connect(seekSlider, &QSlider::sliderMoved, [&](int position) {
if (seekSlider->isSliderDown())
player->setPosition(position * 1000);
});
// 音频准备就绪后,获取音频的总时长(ms)
QObject::connect(player, &QMediaPlayer::mediaStatusChanged, [=](QMediaPlayer::MediaStatus status) {
if (status == QMediaPlayer::BufferedMedia) {
qint64 duration = player->duration();
qDebug() << duration;
return;
}
});
QObject::connect(playButton, &QPushButton::clicked, [=]()
{
if (player->state() == QMediaPlayer::PlayingState)
player->pause();
else
player->play();
});
QVBoxLayout* layout = new QVBoxLayout;
layout->addWidget(playButton);
layout->addWidget(seekSlider);
window.setLayout(layout);
window.setWindowTitle("QtPlayMusic");
window.show();