2

I'm trying to use pygame.mixer.music.load to load an audio file and play it. However, even though the file exists and is playable, I'm still getting a "No such file or directory" error.

Here is the snippet of code:

import os
import pygame
import tempfile
from pydub import AudioSegment

tmp_file = tempfile.NamedTemporaryFile(suffix=".mp3", delete=False)
bgm = AudioSegment.from_mp3(r"C:\Users\creep\sound.mp3")
bgm = bgm + 10
bgm.export(tmp_file.name, format='mp3')

print(f"{os.path.exists(tmp_file.name)=}")

pygame.mixer.init()
pygame.mixer.music.load(tmp_file.name)
pygame.mixer.music.play()
> python .\test_so.py
pygame 2.5.1 (SDL 2.28.2, Python 3.11.4)
Hello from the pygame community. https://www.pygame.org/contribute.html
os.path.exists(tmp_file.name)=True
Traceback (most recent call last):
  File "C:\Users\creep\work\test_so.py", line 15, in <module>
    pygame.mixer.music.load(tmp_file.name)
pygame.error: No such file or directory: 'C:\Users\creep\AppData\Local\Temp\tmpbux7qvnu.mp3'.
>>> import pygame
pygame 2.5.1 (SDL 2.28.2, Python 3.11.4)

Double-checked that the file exists in two different directories:

  • C:\Users\creep\sound.mp3
  • C:\Users\creep\AppData\Local\Temp\tmpbux7qvnu.mp3

Additional Information

Interestingly, when I run the following code snippet, the audio file plays successfully:

import pygame
import time

pygame.mixer.init()
pygame.mixer.music.load(r"C:\Users\creep\AppData\Local\Temp\tmpbux7qvnu.mp3")
pygame.mixer.music.play()
time.sleep(5)
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
  • `NamedTemporaryFile` creates a new random name each time you run the program. Are you sure this is ALL of your code? My guess is there's more going on here. – Tim Roberts Aug 29 '23 at 01:09
  • Actually, this is not all of it, but it is the minimum code that will reproduce the problem I encountered. Also, the name of this temporary file changes every time, so I check the files I check accordingly. – Creeper Saviour Aug 29 '23 at 01:19
  • But why does the error say " line 1"? Are you running this from inside an IDE? – Tim Roberts Aug 29 '23 at 01:47
  • The error says `File "", line 1, in `. But in the posted code, line 1 is `import pygame`. It's very hard to help when you don't share your real code. – John Gordon Aug 29 '23 at 01:48
  • You are certainly right. I used interactive python to create the minimal code to ask the question, hence the error. I have now fixed it and if you would like to take a look at it. – Creeper Saviour Aug 29 '23 at 12:51
  • Try `tmp_file.close()` before trying to play it? Maybe the open file handle is breaking things. – Random Davis Aug 31 '23 at 18:34
  • @Random Davis Thanks, you are right, by closing the tmp_file before calling music.load(), the music played. Is it because the file was locked by tempfile? – Creeper Saviour Sep 01 '23 at 09:09

0 Answers0