Skip to main content
 首页 » 编程设计

python之pygame.mixer.music.pause 应该以我的方式工作吗

2024年11月01日15oomusou

我正在开发一个用 python 3 编写的游戏,pygame。我想介绍一个功能,玩家可以按S暂停游戏进程(场景和音乐),再按一下继续。

但是我发现 pygame.mixer.music.pause() 从来没有工作过,因此 pygame.mixer.music.get_busy() 总是 True。

stop() 有效,但我仍然需要 pause() 以便我可以从音乐暂停的地方继续。

下面是我为缩小问题的可能范围而编写的程序:

import pygame 
import random,sys 
from pygame.locals import * 
 
''''conclusion: pause() is not working(seems it triggers nothing, and  
as a result, get_busy() is not working with pause() ) 
''' 
 
# Define some colors 
black    = (   0,   0,   0) 
white    = ( 255, 255, 255) 
red      = ( 255,   0,   0) 
blue     = (   0,   0, 255) 
purple = (159, 0, 197) 
 
bgColor= (0,   0,   0) 
textColor = (250, 250, 255) 
 
width = 600  
height = 600 
 
def end(): 
    pygame.quit() 
    sys.exit() 
 
def drawText(text, font, surface, x, y): 
    textobj = font.render(text, 1, textColor) 
    textrect = textobj.get_rect() 
    textrect.topleft = (x, y) 
    surface.blit(textobj, textrect) 
 
pygame.init() 
screen = pygame.display.set_mode([width,height]) 
 
pygame.mixer.music.load('background.mid')   
font = pygame.font.SysFont(None, 48) 
 
clock = pygame.time.Clock() 
 
pygame.mixer.music.play(-1, 0.0) 
pygame.mixer.music.set_volume(0.5) 
paused=False 
while True:  #game loop when the game is playing.     
    if not pygame.mixer.music.get_busy(): #is not playing 
        print("Not playing") 
    for event in pygame.event.get():  
        if event.type == pygame.QUIT:  
            end();        
        elif event.type == KEYUP:     
            if event.key == K_ESCAPE: 
                end()    
            elif event.key == K_s:     
                print("pause.") 
                #pygame.mixer.music.pause()  
                pygame.mixer.music.stop() 
 
 
    screen.fill(bgColor) 
    pygame.display.flip()  
    clock.tick(40)          

请您参考如下方法:

最后,我尝试了其他格式的背景音乐。我将音乐格式从 midi 更改为 mp3 或 ogg,pause() 起作用了。所以这里的问题是格式。

此外,get_busy() 并不完全按照 pygame 文档中的描述执行:pause() 和 unpause() 不会更改 get_busy() 的返回值。