首页 > 解决方案 > Pygame 声音对象已创建但未播放

问题描述

在游戏的游戏过程中,每次正确或错误的点击都应该播放声音。调试说它已加载但不播放声音。请帮忙

SOUNDS_METAL = ["assets/sounds/metal_1.ogg",
                "assets/sounds/metal_2.ogg"]

SOUNDS_GLASS = ["assets/sounds/glass_1.ogg",
                "assets/sounds/glass_2.ogg"]

SOUNDS_PLASTIC = ["assets/sounds/plastic_1.ogg",
                  "assets/sounds/plastic_2.ogg"]

SOUNDS_PAPER = ["assets/sounds/paper_1.ogg",
                "assets/sounds/paper_2.ogg"]

SOUNDS_FX = ["assets/sounds/fx_pop.ogg",
             "assets/sounds/fx_error.ogg"]

SOUNDS = [SOUNDS_METAL, SOUNDS_GLASS, SOUNDS_PLASTIC, SOUNDS_PAPER, SOUNDS_FX]
.
.
.
def collision_detector(mouse_pos, target, points, bin_type):
    """checkt wether or not the click is inside the target area"""
    if target[0][0] < mouse_pos[0] < target[0][1]:
        if target[1][0] < mouse_pos[1] < target[1][1]:
            debuginfo("CORRECT HIT")
            points += 1
            debuginfo(f"POINTS: {points}")
            sound_effectplayer(bin_type)
            main(points)
.
.
.
def new_rubbish_maker():
    """creates the ryubbish object"""
    global MAIN_RUBBISH
    MAIN_RUBBISH = random.choice(ALL_RUBBISH)
    sound_effectplayer("new_item")

def sound_effectplayer(object_type):
    """plays the sound effects"""
    global sound_effect
    debuginfo(f"MUSIC OBJECT TYPE: {object_type}")
    if object_type == "metal":
        sound_effect = pygame.mixer.Sound(random.choice(SOUNDS_METAL))
        debuginfo(f"EFFECT: {sound_effect}")
    elif object_type == "plastic":
        sound_effect = pygame.mixer.Sound(random.choice(SOUNDS_PLASTIC))
        debuginfo(f"EFFECT: {sound_effect}")
    elif object_type == "paper":
        sound_effect = pygame.mixer.Sound(random.choice(SOUNDS_PLASTIC))
        debuginfo(f"EFFECT: {sound_effect}")
    elif object_type == "glass":
        sound_effect = pygame.mixer.Sound(random.choice(SOUNDS_GLASS))
        debuginfo(f"EFFECT: {sound_effect}")
    elif object_type == "bad":
        sound_effect = pygame.mixer.Sound(SOUNDS_FX[1])
        debuginfo(f"EFFECT: {sound_effect}")
    elif object_type == "new_item":
        sound_effect = pygame.mixer.Sound(SOUNDS_FX[0])
    sound_effect.play()

完整代码:https ://gitlab.com/Gote/game

标签: pythonpygame

解决方案


添加 pygame.mixer.init()sound_effectplayer函数的最顶部,使其看起来像这样:

def sound_effectplayer(object_type):
    pygame.mixer.init()
    . . .

推荐阅读