1

I am unable to remove a file using os.remove() using the following code,

import pygame
from pygame.mixer import *
import os
from pygame import mixer

def play_music(music_file, volume):
    with open(music_file, 'wb') as f:
        f.write(spoken_text['AudioStream'].read())
        f.close()

    mixer.init()
    mixer.music.load(music_file)
    mixer.music.play()
    #pygame.mixer.init()
    while pygame.mixer.music.get_busy(): 
        pygame.time.Clock().tick(10)
    else:
        os.remove(music_file)
music_file = "C:/CBot/output.mp3"
volume = 0.4
play_music(music_file, volume)

The following error is shown:

PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:/CBot/output.mp3'
AFRAH
  • 11
  • 1

1 Answers1

1

The file cannot be deleted because it is currently in use by your application. You have to unload the music file. The comments to your question mention that you need to call pygame.mixer.music.stop(). This is wrong. See the documentation of pygame.mixer.music.stop():

Stops the music playback if it is currently playing. It won't unload the music.

You have to call pygame.mixer.music.unload():

This closes resources like files for any music that may be loaded.

pygame.mixer.music.unload()
os.remove(music_file)
Rabbid76
  • 202,892
  • 27
  • 131
  • 174