问题
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