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

Asked

Viewed 1,934 times

2

I was touching the Pygame and when performing 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 Ide’s like Pycharm for example, it runs normally. Someone knows what might be?


OBS: I installed Pygame normally in the virtual environment and the.mp3 file is in the same folder as the.py file, I tried using the mixer.load() both with the file name, and stating the path.

  • Your error photo missed the most important line, the last one! Please edit the question and add the rest of the error. Also, put it in text format, not image format.

  • @nosklo Ready, the error is in text mode, but the error lines were only those of the same photo, no more.

1 answer

1


It is likely that the IDE you are using does not use as the current directory the directory where the script is, so when trying 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 complete file path .mp3 in your code, so it can be run 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')
  • It worked by placing the full file path and also keeping the original file name. Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.