Pygame does not run a. mp3 file and returns pygame-error

Was messing with Pygame and when running a program that plays music:

from pygame import mixer

mixer.init()
mixer.music.load('ex021.mp3') # Dark Souls III Soundtrack OST - Main Theme.mp3
mixer.music.play()
input()

It returns me the following error:

Exception has occurred: pygame.error
Couldn't open 'ex021.mp3'
  File "/home/alanmaxwell/Documentos/Projects/VS Code/curso-python3/Mundo 01: Fundamentos/ex021.py", line 8, in <module>
    mixer.music.load('ex021.mp3') # Música - Dark Souls III Soundtrack OST - Main Theme.mp3
  File "/usr/lib/python3.7/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/usr/lib/python3.7/runpy.py", line 96, in _run_module_code
    mod_name, mod_spec, pkg_name, script_name)
  File "/usr/lib/python3.7/runpy.py", line 263, in run_path
    pkg_name=pkg_name, script_name=fname)

Only in VS Code, in other IDEs like Pycharm for example, it runs normally. Does anyone know what it can be?


Note: I installed Pygame normally in the virtual environment and the.mp3 file is in the same folder as the arquivo.py, I have tried to use mixer.load() both with the file name, and informing the path.

Author: Alan Maxwell, 2019-02-21

1 answers

It is likely that the IDE you are using does not use as the current directory the directory where the script is, so when you try to open the file without specifying the path, as you are doing, it will not be found.

Try running the following script, to test if this is the case:

import os; print(os.getcwd()) # mostra o diretorio atual

If it does not show the same path where the script is, then it is confirmed that this is your problem.

To fix there are some ways:

  1. put the full path of the .mp3 file in your code, so that it can be executed regardless of what the current directory is.
  2. detect the script path and use it (using , for example, os.path.join(os.path.dirname(__file__), 'ex021.mp3')
 1
Author: nosklo, 2019-02-21 17:59:22