简体   繁体   English

检查使用SDL2播放的音乐

[英]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. 使用SDL制作简单的游戏,我从程序开始就在后台播放音乐,但是我希望能够检查音乐何时停止播放,以便可以开始下一首曲目。 I'm using the SDL_mixer library to load and play the music. 我正在使用SDL_mixer库来加载和播放音乐。

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. 我正在我称为音乐的类中加载和播放音乐,在类构造函数中将歌曲定义为NULL,然后为其指定曲目名称,并在该类的“ loadTrack”方法中播放它。 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. 我想在该类中使用另一个可以调用的方法,如果轨道已完成播放,则返回true;如果仍在播放,则返回false。 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. SDL_Mixer具有Mix_PlayingMusic()来检查音乐是否正在播放。 But since you pass -1 to Mix_PlayMusic , it loops and plays forever, never stops. 但是,由于您将-1传递给Mix_PlayMusic ,它会循环播放并永远播放,永远不会停止。

I think you can "manually" restart the song by passing 1 (play once) instead of -1 to Mix_PlayMusic . 我认为您可以通过将1(播放一次)而不是-1传递给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). 但是,这将在每次重新启动之间造成很小的静音间隔(如果您的游戏以60fps的速度运行,则大约需要1帧时间〜1 / 60s)。 So if you simply want to loop music seamlessly, better let SDL_Mixer do it rather than doing it by hand like this. 因此,如果您只是想无缝地循环播放音乐,最好让SDL_Mixer来做,而不要像这样手动进行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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