You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Pygame的文本游戏音效播放报错及字典调用问题咨询

Fix TypeError When Playing Room-Specific Sounds in Pygame

Root Cause

The error TypeError: descriptor 'play' for 'pygame.mixer.Sound' objects doesn't apply to a 'str' object happens because you’re using pygame.mixer.Sound.play() incorrectly. play() is an instance method—you need to call it on a created Sound object, not directly on the Sound class, and not by passing a filename string to it.

Solution

Instead of storing just sound filenames in your dictionary, preload each sound into a pygame.mixer.Sound instance first. Then retrieve the preloaded instance and call play() when entering a room.

Step 1: Preload Sounds into Your Dictionary

import pygame

# Initialize pygame mixer first (required before loading sounds)
pygame.mixer.init()

# Map room names to preloaded Sound instances
room_sounds = {
    "room1": pygame.mixer.Sound("effect1.wav"),
    "room2": pygame.mixer.Sound("effect2.wav"),
    "room3": pygame.mixer.Sound("effect3.wav"),
    # Add your remaining 9 rooms and their corresponding sounds here
}

Step 2: Play the Sound on Room Entry

When the player enters a room, grab the Sound instance from the dictionary and call play() on it:

# Example: Player enters room3
current_room = "room3"
selected_sound = room_sounds.get(current_room)
if selected_sound:
    selected_sound.play()
else:
    print(f"No sound assigned to {current_room}")

Key Tips

  • Ensure your sound file paths are correct (use relative paths like sounds/effect3.wav if files are in a subfolder).
  • Preloading all sounds at game start avoids lag when switching rooms, which is perfect for 12 rooms.
  • If you need to stop a sound mid-play, use selected_sound.stop() on the same instance.

内容的提问来源于stack exchange,提问作者Thom

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 15:25:15