Cannot load music in Pygame

家住魔仙堡 提交于 2021-01-27 20:09:06

问题


The code I am using is this:

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')

Unfortunately, I get this error:

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'

I have also looked at this question and its answer. They are, unfortunately, not helpful because the .mp3 was, to begin with, in the same file as my Python script. How can I get PyGame music to work correctly?


回答1:


mp3 not recognized

Not sure if this is the problem, since it seems to me you are using windows, but check the pygame music docs. They say:

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.

So try to convert the file to another format, like WAV or OGG. Maybe it works.

use full path

The error you posted is the error pygame gives when the file is not found. So maybe @Matt in his comment is right.
Try to use the full path, and build it with the help of the os.path functions, they are safer and less error prone than writing the full path by hand.
If you are sure that the music file is in the same directory where is the python script, you can get its full path by doing: os.path.abspath("timer_end.mp3")

As last resource, the following code will extrapolate the path of the python file and build the full path of the file music assuming that it is in the same directory. It should work even if you launch the python script from another directory.

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



回答2:


I believe this error is caused because the file is not found. For example take the Windows sample Kalimba.mp3. Here I have a python file in the Sample Music location that is called from another location.

import pygame
pygame.mixer.init()
pygame.mixer.music.load('Kalimba.mp3')

This results in Couldn't open 'Kalimba.mp3' error. If I change to the full path

import pygame
pygame.mixer.init()
pygame.mixer.music.load('<full path>Kalimba.mp3')

This runs without an error. I recommend that you use a music library as described in this tutorial to organize your asset files.



来源:https://stackoverflow.com/questions/56212721/cannot-load-music-in-pygame

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!