Umbra
Umbra

Reputation: 123

How to access the meta data of QMediaPlayer?

I want to access the metadata of the mp3 file and put it in the labels but the program doesn't read it. I read http://doc.qt.io/qt-5/qmediametadata.html. I wrote this code but it doesn't work properly (besides QFileInfo).

path = item->text(); //text is a path from QFileDialog::getOpenFileName
/*QMediaPlayer*/ sound.setMedia(QUrl::fromLocalFile(path));
 QFileInfo info(path);

        ui->label_3->setText(sound.metaData("Title").toString());
    if (ui->label_3->text()=="")
        ui->label_3->setText(sound.metaData("AlbumTitle").toString());
    if (ui->label_3->text()=="")
    ui->label_3->setText(info.baseName());

 ui->label_5->setText(sound.metaData("Author").toString());
    if (ui->label_5->text()=="")
        ui->label_5->setText(sound.metaData("AlbumArtist").toString());
    if (ui->label_5->text()=="")
        ui->label_5->setText(sound.metaData("Composer").toString());

Library and multimedia are added.

Upvotes: 1

Views: 1279

Answers (1)

scopchanov
scopchanov

Reputation: 8399

Cause

It takes time for the media to be loaded after calling QMediaPlayer::setMedia, hence requesting the meta data right after the media has been set results in:

QVariant(Invalid)

Solution

I would suggest you to wait for the media to be loaded by connecting to the QMediaPlayer::mediaStatusChanged and reading the meta data once the status becomes QMediaPlayer::LoadedMedia.

Note: If you make sound a local variable, it would be destroyed when it goes out of scope. Better use auto *sound = new QMediaPlayer(this);.

Example

Here is an example I have prepared for you of how you could change your code in order to implement to proposed solution:

connect(sound, &QMediaPlayer::mediaStatusChanged, [this, sound, info](QMediaPlayer::MediaStatus status){
    if (status == QMediaPlayer::LoadedMedia) {
        ui->label_3->setText(sound->metaData("Title").toString());
        if (ui->label_3->text()=="")
            ui->label_3->setText(sound->metaData("AlbumTitle").toString());
        if (ui->label_3->text()=="")
            ui->label_3->setText(info.baseName());

        ui->label_5->setText(sound->metaData("Author").toString());
        if (ui->label_5->text()=="")
            ui->label_5->setText(sound->metaData("AlbumArtist").toString());
        if (ui->label_5->text()=="")
            ui->label_5->setText(sound->metaData("Composer").toString());
    }
});

Upvotes: 1

Related Questions