3

I am asking this question as i'm attempting to create my own and first twitch bot (newbie programmer). What I wish to do is when the user requests a song from youtube, I rip the audio from the youtube video from another module i'm using and then I will play it through my program using pygame, my only issue is that after the song is done playing I wish to delete it so i'm not wasting space on my computer by downloading and keeping all song requests from users in my project folder. The only problem is I get the WinError 32 about deleting a file used by another process.

Here is the code i've developed so far, I have no idea how I would close the file to be able to delete it, i've tried moving the music_file after calling the function and no luck there.

import pygame as pg
import os

def play_music(music_file, volume):

freq = 44100
bitsize = -16
channels = 2
buffer = 2048
pg.mixer.init(freq, bitsize, channels, buffer)
pg.mixer.music.set_volume(volume)
clock = pg.time.Clock()

pg.mixer.music.load(music_file)
pg.mixer.music.play()
while pg.mixer.music.get_busy():
    clock.tick(30)
else:
    os.remove(music_file)

music_file = "C:/Users/Devin/PycharmProjects/Fun/Milk.mp3"

volume = 0.4

play_music(music_file, volume)

and the error:

PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:/Users/Devin/PycharmProjects/Fun/Milk.mp3'
D. Harris
  • 31
  • 2
  • If you were using a *real* operating system (with reference-counted inodes), you wouldn't have this problem -- could delete the directory entry for the file, and the disk space would only be deallocated after it was actually closed everywhere. :) – Charles Duffy Jan 25 '16 at 20:34
  • First: Fix your identation. – tglaria Jan 25 '16 at 20:36
  • 3
    Second: are you closing the file after it finished playing? – tglaria Jan 25 '16 at 20:36
  • 1
    Use `pg.mixer.quit()` at the end of `play_music()`. – Kenly Jan 25 '16 at 21:47
  • Indentation messed up whenever I tried to copy out of PyCharm straight into stack overflow. the pg.mixer.quit() worked, thank you so much for you help. – D. Harris Jan 25 '16 at 21:50

0 Answers0