3

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.

László Papp
  • 51,870
  • 39
  • 111
  • 135
user3430722
  • 345
  • 1
  • 5
  • 12

1 Answers1

0

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);
}
user3430722
  • 345
  • 1
  • 5
  • 12
  • 1
    Actually, this has nothing to do with type conversion. QMediaPlayer works asynchronously. That means that by the time you are calling ->duration(), the file was not loaded yet and has not started playing yet. At that point in the execution, QMediaPlayer simply does not know the duration yet. Unfortunately, other than deriving, there is no simple method to make the loading of the file blocking. – TheSHEEEP Nov 29 '16 at 09:46