【问题标题】:Why does this code to play a sound using Python and Pygame on mac not load the file and crash?为什么这段代码在 mac 上使用 Python 和 Pygame 播放声音时不会加载文件并崩溃?
【发布时间】:2017-12-29 09:28:14
【问题描述】:

我查看了这个网站上的几个问题和多个其他资源,发现这段代码可以用来用 pygame 播放声音,但我遇到了一些问题。

import pygame
pygame.init()
song = pygame.mixer.Sound('sound.wav')
clock = pygame.time.Clock()
song.play()
while True:
    clock.tick(60)
pygame.quit()

我已经尝试了两个文件(“sound.wav”和“sound.mp3”),以及单引号和双引号,但它仍然不起作用。当我尝试文件的路径时,Python 崩溃了。有什么我可以更改或添加到此代码以使其工作的东西,如果没有,是否有其他解决方案?

我得到的错误是它无法加载文件。

编辑:现在无论我传递给 pygame.mixer.Sound() 什么,它都会崩溃,说 Python 意外退出。

【问题讨论】:

  • 您可能应该尝试重新安装 pygame。为什么不能正确安装 pip?你有什么错误?
  • 我重新安装了 pygame 并安装了 Pip。显然,我的命令行工具出现了问题,但是随着一些应用程序的删除/重新安装和重新启动,事情又开始工作了。但是,声音仍然不起作用。

标签: macos python-3.x audio pygame


【解决方案1】:

在pygame中你不能使用相对文件路径,除非你使用os。

import pygame,os
dir = os.path.dirname(__file__)
pygame.init()
song = pygame.mixer.Sound(os.path.join(dir,'./sound.wav'))
clock = pygame.time.Clock()
song.play()
while True:
    clock.tick(60)
pygame.quit()

【讨论】:

  • 当我这样做时,它说“Python 意外退出”
  • @TrumpetDude 查找并尝试了它,尝试将您的文件转换为 .ogg 并使用这个。为我工作。
【解决方案2】:

使用pygame播放声音,请确保您的代码也包含停止音乐代码,如果您的代码只包含开始音乐,那么python将不会播放该声音。

例子。

from pygame import mixer

mixer.init()
mixer.music.load("song.mp3")
mixer.music.set_volume("0.5")
mixer.music.play()

#comment ::: 如果您只有此代码,那么您的声音将不会播放您#应该添加代码以在任何时候停止它,例如 brlow..

st = input("type s to stop")
if(st == "s"):
   mixer.music.stop()

#现在这段代码可以工作了

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多