1

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.

Umbra
  • 123
  • 1
  • 5

1 Answers1

1

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());
    }
});
scopchanov
  • 7,966
  • 10
  • 40
  • 68
  • Thanks, for suggests, but I get the message: " 'sound' in capture list does not name a variable.". I store sound as a QMediaPlayer variable in the mainwindow.h file. Should I store it somewhere else to make it work? – Umbra Nov 02 '18 at 20:43
  • @Nve, Change `[this, sound, info]` to `[this, info]`. – scopchanov Nov 02 '18 at 21:57
  • 1
    I have also added & to sound (&sound) and now it's fully working, thanks. – Umbra Nov 03 '18 at 11:26