Pygame music pause/unpause toggle

蓝咒 提交于 2021-02-16 20:56:17

问题


Okay here's my code:

def toggleMusic():

    if pygame.mixer.music.get_busy():
        pygame.mixer.music.pause()

    else:
        pygame.mixer.music.unpause()

---event handling---

if pressed 'm' it should toggle whether the music is paused and not paused

toggleMusic()

It can pause the music but not unpause, any explanation?


回答1:


Had the same problem. For others' reference, my solution was to use a simple class.

class Pause(object):

    def __init__(self):
        self.paused = pygame.mixer.music.get_busy()

    def toggle(self):
        if self.paused:
            pygame.mixer.music.unpause()
        if not self.paused:
            pygame.mixer.music.pause()
        self.paused = not self.paused

# Instantiate.

PAUSE = Pause()

# Detect a key. Call toggle method.

PAUSE.toggle()



回答2:


It doesn't unpause the music because pygame.mixer.music.pause() doesn't affect the state of pygame.mixer.music.get_busy().

To get the behavior you are looking for you will need to your maintain your own variable which keeps track of the paused/unpaused state. You can do this in a class:

class mixerWrapper():

    def __init__(self):
        self.IsPaused = False

    def toggleMusic(self):
        if self.IsPaused:
            pygame.mixer.music.unpause()
            self.IsPaused = False
        else:
            pygame.mixer.music.pause()
            self.IsPaused = True


来源:https://stackoverflow.com/questions/25221036/pygame-music-pause-unpause-toggle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!