Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
933 views
in Technique[技术] by (71.8m points)

qmediaplayer - play background music in a loop Qt

I want to play background music continually in a loop until the game ends.

in the header file:

    QMediaPlayer * music = new QMediaPlayer();

in the cpp file:

    startGame(){
    music->setMedia(QUrl("qrc:/sounds/backgroundmusic.mp3"));
    music->play();  }

   stopGame(){
   music->stop(); }

Right now my music plays thru to the end but does not restart. How can I get it to loop over again again? Is there a QMediaPlayer member I can use, or should I run it in a while loop, or what?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Sounds like what you want is QMediaPlaylist. QMediaPlaylist allows you to control the playback mode, and in this case you would use Loop. This approach has other advantages too, such as CurrentItemInLoop. CurrentItemInLoop will play the current playlist item in a loop, meaning that if you add more songs in the future you can select a song then loop only that track. Thus, you only need a single playlist for most needs. Below is some example code, I do not currently have a means to test it though (No Qt multimedia extensions installed on this machine). Should demonstrate the point reasonably well though.

QMediaPlaylist *playlist = new QMediaPlaylist();
playlist->addMedia(QUrl("qrc:/sounds/backgroundmusic.mp3"));
playlist->setPlaybackMode(QMediaPlaylist::Loop);

QMediaPlayer *music = new QMediaPlayer();
music->setPlaylist(playlist);
music->play();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...