简体   繁体   English

Pygame 音乐暂停/取消暂停切换

[英]Pygame music pause/unpause toggle

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如果按下“m”,它应该切换音乐是暂停还是不暂停

toggleMusic()

It can pause the music but not unpause, any explanation?它可以暂停音乐但不能取消暂停,有什么解释吗?

It doesn't unpause the music because pygame.mixer.music.pause() doesn't affect the state of pygame.mixer.music.get_busy() .它不会取消暂停音乐,因为pygame.mixer.music.pause()不会影响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

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()

this one is good, i use it for games这个不错,我用它玩游戏

source https://youtu.be/kzTloDq1FiQ来源https://youtu.be/kzTloDq1FiQ

is_paused = False

def toggle_pause():
    global is_paused
    if is_paused == True:
        is_paused = False
    else:
        is_paused = True

wn.listen()
wn.onkeypress(toggle_pause, " ")

while True:
    if not is_paused:
        bob.fd(1)
        bob.lt(1)
    else:
        wn.update()

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

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