and then stops.
By-the-Way: Queuing It Up!
If you want to play only a couple songs, you can use the queue method. You simply
load and play the first song, and the first song begins to play immediately. Then you
load and queue a second song. The method to queue a song is
pygame.mixer.music.queue('filename'). When the first song stops playing,
the second song starts playing right away.
You can queue only one song at a time. If you queue a third song, before the second
song starts playing, the second song is “wiped” from the queue list.
Storing Your Music on a Removable Disk
Music files, especially if they are in uncompressed WAV file format, can take up a great deal of disk
space. Once again, your SD card with Raspbian may not have the space needed to hold the music files
you want to play. You can fix this problem by using a removable drive with your Python script.
Just as you used a removable hard drive in the HD image presentation script, you can use it in your
music script. The only change needed is to set up variables which point to the disk and directory
holding your music.
Be aware that you need to create a music directory before you run your script. To create a music
directory, you open LXTerminal, type a command similar to mkdir /home/pi/music, and press
Enter.
Unlike in the HD presentation script, you cannot simply unmount the drive at the end of the script.
Playing music from a removable drive can introduce a few problems with keeping files open and can
cause the drive to fail to unmount. However, you can clean up the umount commands from the HD
presentation script and put them into a function (where they should have been in the first place).
Here’s what this looks like:
Click here to view code image
# Gracefully Exit Script Function #################
#def Graceful_Exit ():
pygame.mixer.music.stop() #Stop any music.
pygame.mixer.quit() #Quit mixer
pygame.time.delay(3000) #Allow things to shutdown
Command = "sudo umount " + MusicDisk
system(Command) #Unmount disk
exit()
The method pygame.mixer.music.stop is called to stop any music from playing. Also, the
mixer is shut down using pygame.mixer.quit. Finally, a delay is added, just to give everything
time to shut down, before the umount command is issued. It’s a little bit of overkill, but properly
unmounting a removable drive with your music is worth it!
Using a Music Playlist
While you could use the os.listdir method used earlier in this hour to load the music files, using
a playlist will give you finer control (and more Python practice). You can create a simple playlist of
the music files to play in a particular order by using either the nano text editor or the IDLE text editor.