Pygame music player playing audio only once then throwing error

Question:

I am trying to use pygame mixer to play audio files as shown in my code below.

from pydub import AudioSegment
from pygame import mixer
import urllib.request
from time import sleep

mixer.init()
urllib.request.urlretrieve("http://www.freemusicloops.co.uk/download.aspx?did=266", "firstfile.wav")
audio1 = AudioSegment.from_wav("firstfile.wav")

mixer.music.load("firstfile.wav")
mixer.music.play()

However, I can only play the file once and then it gives the following error.

PermissionError: [Errno 13] Permission denied: 'firstfile.wav'

How can I fix this error and play the same audio multiple times without having to delete it and run the code again?

Asked By: Tegh Singh

||

Answers:

As discussed in the comments, if you are running your program again and again from the top, then the two solutions I see are either loading the file first and then containing the playing of it to an inner loop within your program (say, game loop) OR unloading the file at then of your program by calling

mixer.music.unload('filename')

where the ‘filename’ is the file you’ve loaded before.

Answered By: Nick S.
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.