I use Qt 5.7
I'm writing Music Player, and have one problem. Method duration()
of QMediaPlayer
always returns 0. How can I fix it?
Example of code:
QMediaPlayer *player = new QMediaPlayer;
player->setMedia(QMediaContent(QUrl(path)));
qDebug() << player->duration(); // returns 0
player->play(); // it works
You cannot do a player->duration()
right after the player->setMedia(QMediaContent(QUrl(path)));
.
Indeed, the QMediaPlayer::setMedia
is asynchronous so if you call the duration right after it, the media won't be set yet and then the duration will be wrong.
From Qt documentation on setMedia:
Note: This function returns immediately after recording the specified source of the media. It does not wait for the media to finish loading and does not check for errors.
When the duration is updated, QMediaPlayer send a signal named durationChanged(qint64 duration)
. So that you need to do is to connect this signal with a lambda or a slot.
For example,
QMediaPlayer *player = new QMediaPlayer(this);
connect(player, &QMediaPlayer::durationChanged, this, [&](qint64 dur) {
qDebug() << "duration = " << dur;
});
QUrl file = QUrl::fromLocalFile(QFileDialog::getOpenFileName(this, tr("Open Music"), "", tr("")));
if (file.url() == "")
return ;
player->setMedia(file);
qDebug() << player->duration();
player->setVolume(50);
player->play();
the first qDebug will write 0 as your but the second in the lambda will write the new duration of the QMediaPlayer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With