title: How to open and close a music file properly for pygame mixer without hanging/freezing Python?
body: <p>I'm developing a music player in Python 2.7 and I have a problem I can not solve.</p>
  
  <p>Sometimes it's necessary to unmount the SD card I'm playing from.
  Since pygame still keeps the last played file open after <em>pygame.mixer.stop()</em> and <em>pygame.mixer.quit()</em>
  commands, it was not possible to unmount the card.</p>
  
  <p>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.</p>
  
  <p>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.</p>
  
  <p>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.</p>
  
  <p>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?</p>
  
  <p>Here is the relevant part of my code. It closes the previous playing session and starts playing a new file.</p>
  
  <pre><code>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 &lt;&gt; 1:
      pygame.mixer.init(frequency=musicforlength.info.sample_rate)
      pygame.mixer.music.set_volume(MainVolume)
      pygame.mixer.music.load(PlayedMp3File)
      pygame.mixer.music.play()
  </code></pre>