I'm developing a music player in Python 2.7 and I have a problem I can not solve.
Sometimes it's necessary to unmount the SD card I'm playing from. Since pygame still keeps the last played file open after pygame.mixer.stop() and pygame.mixer.quit() commands, it was not possible to unmount the card.
So I modified my code to use the file open and close commands to be able to properly close the played file before the unmount. This way the unmount is working fine.
My issue is with this solution that python always hangs during the playback of the first music. There are no any exceptions or error messages, the playback just stops and the program doesn't respond any user input, even the Ctrl+C doesn't work to quit the execution from shell.
This hanging always happens at a random time, somewhere between 1 and 40 seconds after the playing has started. If I open the file directly with the pygame.mixer.music.load(myfile) command, not using the open/close solution, I never have any hanging, the program plays properly even for several hours long.
What solution shall I use to be able to properly close the played file (to be able to unmount the memory card) and also avoid hanging of the program?
Here is the relevant part of my code. It closes the previous playing session and starts playing a new file.
FailedMusicLoad = 0
pygame.mixer.music.stop()
pygame.mixer.stop()
pygame.mixer.quit()
try:
PlayedMp3File.close()
except AttributeError:
pass
try: # test if selected music file can be loaded
PlayedMp3File = open(Selectedmp3)
except IOError:
FailedMusicLoad = 1
if FailedMusicLoad <> 1:
pygame.mixer.init(frequency=musicforlength.info.sample_rate)
pygame.mixer.music.set_volume(MainVolume)
pygame.mixer.music.load(PlayedMp3File)
pygame.mixer.music.play()