pygame.mixer.music.load(filename) does not release the file after the music has been loaded

846 Views Asked by At

I would like to have the pygame.mixer.music.load(filename) command release the file once the music has been uploaded. Since it does not release the file, I can not delete the file. I have attached a very simple program illustrating the problem.

import pygame
import os

pygame.mixer.init()

# load the music
pygame.mixer.music.load('music.mp3')

# loop the music
pygame.mixer.music.unpause()
pygame.mixer.music.play(-1)

# delete the music.mp3 file
if os.path.exists('music.mp3'):

    # when we get to this point, the file is still attached to the
    # pygame.mixer.music.load() command and can't be deleted.
    # how can I unlink pygame.mixer.music.load() and the file music.mp3
    # so that the file can be deleted?

    os.remove('music.mp3')
    # ERROR: [WinError 32] The process cannot access the file because it is 
    #                      being used by another process: 'music.mp3'

Thanks in advance for any help you can provide.

1

There are 1 best solutions below

0
Rabbid76 On

Placing pygame.mixer.music.unload() before the os.remove('music.mp3') line of code solved the problem.