Search code examples
c++qtqt5qmediaplayerqtmultimedia

How to get the total time of an audio file?


How to get the total time of an audio file? I am trying this:

QMediaPlayer* audioPlayer = new QMediaPlayer();
audioPlayer->setMedia(QUrl::fromLocalFile("F:/Audio/mysong.mp3"));
audioPlayer->duration(); // return 0

but all the time the function returns 0. I use the latest version Qt on Windows 8.


Solution

  • Yes, i found error, it was to type conversion (qint64) In order to get the duration you need to use "durationChanged" signal.

    //get duration in durationChanged signal.
    connect(audioPlayer, SIGNAL(positionChanged(qint64)), this, SLOT(setPositionSlider(qint64)));
    //Old function
    void Widget::setPositionSlider(qint64 i)
    {
        ui->PositionSlider->setValue(i / duration * 100); //0 I thought it was converted into double.
    }
    //New function
    void Widget::setPositionSlider(qint64 i)
    {
        ui->PositionSlider->setValue(i / 1000);
    }