Skip to main content
 首页 » 编程设计

python之无法在 Pygame 中加载音乐

2024年11月24日10think

我使用的代码是这样的:

import pygame 
assert pygame.init()==(6,0) 
pygame.mixer.init() 
from pygame.locals import * 
from time import sleep 
import os 
pygame.mixer.music.load('timer_end.mp3') 

不幸的是,我得到了这个错误:

Traceback (most recent call last): 
  File "C:\Python37\Lib\timer.py", line 60, in <module> 
    pygame.mixer.music.load('timer_end.mp3') 
pygame.error: Couldn't open 'timer_end.mp3' 

我也看过this question及其答案。不幸的是,它们没有帮助,因为 .mp3 最初与我的 Python 脚本位于同一文件中。如何让 PyGame 音乐正常工作?

请您参考如下方法:

mp3 无法识别

不确定这是否是问题所在,因为在我看来您使用的是 Windows,但请检查 pygame music docs .他们说:

Be aware that MP3 support is limited. On some systems an unsupported format can crash the program, e.g. Debian Linux. Consider using OGG instead.

因此请尝试将文件转换为另一种格式,例如 WAV 或 OGG。也许它有效。

使用完整路径

您发布的错误是找不到文件时 pygame 给出的错误。所以也许@Matt 在他的评论中是对的。
尝试使用完整路径,并借助os.path函数构建它,它们比手写完整路径更安全,更不容易出错。
如果您确定音乐文件与 python 脚本位于同一目录中,则可以通过执行以下操作获取其完整路径:os.path.abspath("timer_end.mp3")

作为最后一个资源,以下代码将推断 python 文件的路径并构建文件 music 的完整路径,假设它位于同一目录中。即使您从另一个目录启动 python 脚本,它也应该可以工作。

filepath = os.path.abspath(__file__) 
filedir = os.path.dirname(filepath) 
musicpath = os.path.join(filedir, "timer_end.mp3") 
pygame.mixer.music.load(musicpath)