简体   繁体   中英

Checking for music playing with SDL2

Using SDL to make a simple game and I have music playing in the background from the start of the program, but I want to be able to check when the music has stopped playing so that the next track can be started. I'm using the SDL_mixer library to load and play the music.

bool loadTrack()
{
    song = Mix_LoadMUS( "backgroundmusic.mp3" ); 
    if (song == NULL)
    {
        return false;
    }
    else
    {
        Mix_PlayMusic(song, -1);
        return true;
    }
}

I'm loading and playing the music in a class I made called music, song is defined in the class constructor as NULL then give it the track name and play it in the "loadTrack" method in that class. I want to use another method in the class that can be called and returns true if the track has finished playing and false if it is still playing. My problem is having no idea how to check if the track is still playing or if the mixer libraries has its own function for checking if it is still playing.

SDL_Mixer has Mix_PlayingMusic() to check if music is playing. But since you pass -1 to Mix_PlayMusic , it loops and plays forever, never stops.

I think you can "manually" restart the song by passing 1 (play once) instead of -1 to Mix_PlayMusic . Then in your main loop, before going to next frame, check if music has stopped playing, so you can either start it again or play another music. However, this will cause a small silence gap between each restart (about 1 frame time ~ 1/60s if your game is running at 60fps). So if you simply want to loop music seamlessly, better let SDL_Mixer do it rather than doing it by hand like this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM