Python Programming for Raspberry Pi, Sams Teach Yourself in 24 Hours

(singke) #1

Now you have your playlist loaded, you have a removable drive with the music ready, and you know
how to load and play the music. But just how do you control the playback of the music?


PyGame provides event handling that will work perfectly for controlling music playback. Using the
.set_endevent method causes an event to queue up after a song has finished playing. This event
is called an “end” event because it is sent to the queue when the song ends. The following is an
example of an entire function that loads the music file, starts playing the music file, and sets an end
event:


Click here to view code image


# Play The Music Function #########################
#
def Play_Music (SongList,SongNumber):
pygame.mixer.music.load(SongList[SongNumber])
pygame.mixer.music.play(0)
pygame.mixer.music.set_endevent(USEREVENT) #Send event when Music Stops

Notice that end event set is USEREVENT. This means that when the music stops playing, the event
USEREVENT will be sent to the event queue.


Checking for the USEREVENT event should be handled in the main body of the Python script. You use
a while loop to keep the music playing and a for loop to check for the song’s end event:


Click here to view code image


while True: #Keep playing the Music ############
for Event in event.get():
#
if Event.type == USEREVENT:
if SongNumber < MaxSongs:
Play_Music(SongList,SongNumber)
SongNumber = SongNumber + 1
if SongNumber >= MaxSongs:
SongNumber = 0 #Start over in PlayList
Play_Music(SongList,SongNumber)
SongNumber = SongNumber + 1

In this example, if the song’s end event, USEREVENT, is found in the event queue, then a couple
checks are made. If the song list has not been fully played (SongNumber < MaxSongs), the next
song in the SongList is played. However, if all the songs have been played, then SongNumber is
set back to 0 (the first file name in the SongList), and the playing of the list starts over.


By-the-Way: Getting Fancy
You have just seen a very simple way to handle playing music in Python. You can get
very fancy with PyGame operations, though. For example, you can use .fadeout to
slowly fade out music at its end and .set_volume to make certain songs (like your
favorites) louder than others.

At this point, the Python music script plays endlessly. To add control for ending the script, you need
to check for another event, such as pressing a key on the keyboard. You do this much the same way
you controlled the HD image presentation script. Here’s what it looks like:


Click here to view code image

Free download pdf