Qt wiki will be updated on October 12th 2023 starting at 11:30 AM (EEST) and the maintenance will last around 2-3 hours. During the maintenance the site will be unavailable.
Seek in Sound File
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);<br />player->setMedia(QUrl::fromLocalFile&amp;#40;"myCoolSong.mp3&quot;&#41;&#41;;<br />player->setVolume(50);<br />player->play(); // music can be heard<br />qDebug() << player->isSeekable(); // is always false<br />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()<br />{<br /> qDebug() << player->isSeekable(); // true<br /> player->setPosition ( 20*1000 );<br />}
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;)<br />{<br /> setMedia(QUrl::fromLocalFile&amp;#40;file&amp;#41;);<br /> if(!isSeekable())<br /> {<br /> QEventLoop loop;<br /> QTimer timer;<br /> timer.setSingleShot(true);<br /> timer.setInterval(2000);<br /> loop.connect(&timer;, SIGNAL (timeout()), &loop;, SLOT (quit()) );<br /> loop.connect(this, SIGNAL (seekableChanged(bool)), &loop;, SLOT (quit()));<br /> loop.exec&amp;#40;&#41;;<br /> }<br />}
When files are loaded with this blocking load method <code>setPosition()</code> can be called right in the next source line.
<code>loadBlocking</code> blocks until signal <code>seekableChanged()</code> is emitted. To avoid a deadlock, maximum waiting time is 2 seconds.