Reputation: 105
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?
Upvotes: 3
Views: 4319
Reputation: 7361
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.
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)
Upvotes: 2
Reputation: 2802
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.
Upvotes: 0