Kinexd
Kinexd

Reputation: 43

QtCreator QMediaPlayer Meta Data returns blank QString

I have a working media player using QMediaPlayer. It can open a song using a QFileDialog then play and pause it. I want to be able to read the metadata of the music files and use them as strings. I know this music has metadata as it shows up in Windows File Explorer. Here is the code that I have.

void MainWindow::playAudioFile(QString openItem){
     player = new QMediaPlayer(this);
     player->setMedia(QUrl(openItem));
     player->setVolume(50);
     player->play();
     QString albumTitle = player->metaData(QMediaMetaData::AlbumTitle).toString();
     ui->albumLabel->setText(albumTitle);
     qDebug()<<player->metaData(QMediaMetaData::Title);

The setting of ui text ends up blank and the qDebug print statement in the Application Output ends up blank. The Application Output in QtCreator also says QVariant(Invalid).

Upvotes: 1

Views: 4280

Answers (2)

George Y.
George Y.

Reputation: 11789

You do not need to start playing the media to get the metadata. However you do need to wait until the media is loaded.

When you call player->setMedia(QUrl(openItem)); the actual loading happens in background (you can see in debugger Qt spawning a bunch of threads). setMedia() however does not wait for the media to be loaded, it simply returns. If you query for metadata right away, it may or may not be available depending on thread scheduling (i.e. depending on whether media has been loaded or not).

To retrieve it reliably, you need to connect to mediaStatusChanged() signal, and wait for the status QMediaPlayer::LoadedMedia - as soon as you receive it, you can query the metadata right there in its slot.

And, to get the best performance, please keep in mind that you can create more than one QMediaPlayer instance at a time.

Upvotes: 3

zeFrenchy
zeFrenchy

Reputation: 6591

Try checking if metadata is indeed available through Qt

if (player->isMetaDataAvailable())
{
  /* YOUR CODE HERE */
}
else
{
  qDebug() << "No metadata.";
}

the Qt Media Player example has all the code you need.

Upvotes: 2

Related Questions