Jump to content

Seek in sound file

From Qt Wiki
Revision as of 10:39, 24 February 2015 by Maintenance script (talk | contribs)


How to Seek in Sound File

I tried to play a sound file not at the beginning but with an offset of 20 seconds.

The following way of setting an offset fails:
player = new QMediaPlayer(this);
player->setMedia(QUrl::fromLocalFile("myCoolSong.mp3"));
player->setVolume(50);
player->play(); // music can be heard
qDebug() << player->isSeekable(); // is always false
player->setPosition ( 20*1000 ); //does not work

It does not work because QMediaPlayer works asynchronously.

As soon as the seek operations are delayed everything works as intended. For example:

CoolPlayer::on_Button1_clicked()
{
qDebug() << player->isSeekable(); // true
player->setPosition ( 20*1000 );
}

To make my life easier I have derived a class MediaPlayer from QMediaPlayer and added a blocking load method:

void MediaPlayer::loadBlocking(const QString &file;)
{
setMedia(QUrl::fromLocalFile&amp;#40;file&amp;#41;);
if(!isSeekable())
{
QEventLoop loop;
QTimer timer;
timer.setSingleShot(true);
timer.setInterval(2000);
loop.connect(&timer;, SIGNAL (timeout()), &loop;, SLOT (quit()) );
loop.connect(this, SIGNAL (seekableChanged(bool)), &loop;, SLOT (quit()));
loop.exec&amp;#40;&#41;;
}
}

When files are loaded with this blocking load method <code&gt;setPosition()</code&gt; can be called right in the next source line.
<code&gt;loadBlocking&lt;/code&gt; blocks until signal <code&gt;seekableChanged()</code&gt; is emitted. To avoid a deadlock, maximum waiting time is 2 seconds.