我对QMediaPlayer的工作原理有一些根本的误解。我认为如果我一个接一个地播放两个音轨,那么应该只播放最后一个。但是有时候顺序是错误的,我听到的是第一首曲目,而不是第二首曲目(单击了第一和第三按钮)。但是在放袋里,我总是看到正确的顺序。您会如何建议我解决这个问题?
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) {
ui->setupUi(this);
player = new QMediaPlayer(this);
connect(player, &QMediaPlayer::mediaStatusChanged, this, [this](auto status) {
QMediaPlayer *ptr = qobject_cast<QMediaPlayer *>(sender());
qDebug() << "mediaStatusChanged: " << status << " currentMedia:" << ptr->currentMedia().request().url().fileName();
});
connect(player, &QMediaPlayer::stateChanged, this, [this](auto status) {
QMediaPlayer *ptr = qobject_cast<QMediaPlayer *>(sender());
qDebug() << "stateChanged: " << status << " currentMedia:" << ptr->currentMedia().request().url().fileName();
});
}
MainWindow::~MainWindow() { delete ui; }
void MainWindow::on_pushButton_clicked() {
qDebug() << " pushButton clicked";
QString trackPath1 = QDir::currentPath() + "/track1.mp3";
QString trackPath2 = QDir::currentPath() + "/track2.mp3";
player->setMedia((QUrl::fromLocalFile(trackPath1)));
player->play();
player->stop();
player->setMedia((QUrl::fromLocalFile(trackPath2)));
player->play();
}
调试输出:
pushButton clicked
mediaStatusChanged: QMediaPlayer::LoadingMedia currentMedia: "track1.mp3"
stateChanged: QMediaPlayer::PlayingState currentMedia: "track1.mp3"
stateChanged: QMediaPlayer::StoppedState currentMedia: "track1.mp3"
stateChanged: QMediaPlayer::PlayingState currentMedia: "track2.mp3"
mediaStatusChanged: QMediaPlayer::BufferedMedia currentMedia: "track2.mp3"
mediaStatusChanged: QMediaPlayer::EndOfMedia currentMedia: "track2.mp3"
stateChanged: QMediaPlayer::StoppedState currentMedia: "track2.mp3"
pushButton clicked
mediaStatusChanged: QMediaPlayer::LoadingMedia currentMedia: "track1.mp3"
stateChanged: QMediaPlayer::PlayingState currentMedia: "track1.mp3"
stateChanged: QMediaPlayer::StoppedState currentMedia: "track1.mp3"
stateChanged: QMediaPlayer::PlayingState currentMedia: "track2.mp3"
mediaStatusChanged: QMediaPlayer::StalledMedia currentMedia: "track2.mp3"
mediaStatusChanged: QMediaPlayer::BufferedMedia currentMedia: "track2.mp3"
mediaStatusChanged: QMediaPlayer::EndOfMedia currentMedia: "track2.mp3"
stateChanged: QMediaPlayer::StoppedState currentMedia: "track2.mp3"
pushButton clicked
mediaStatusChanged: QMediaPlayer::LoadingMedia currentMedia: "track1.mp3"
stateChanged: QMediaPlayer::PlayingState currentMedia: "track1.mp3"
stateChanged: QMediaPlayer::StoppedState currentMedia: "track1.mp3"
stateChanged: QMediaPlayer::PlayingState currentMedia: "track2.mp3"
mediaStatusChanged: QMediaPlayer::StalledMedia currentMedia: "track2.mp3"
mediaStatusChanged: QMediaPlayer::BufferedMedia currentMedia: "track2.mp3"
mediaStatusChanged: QMediaPlayer::EndOfMedia currentMedia: "track2.mp3"
stateChanged: QMediaPlayer::StoppedState currentMedia: "track2.mp3"