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

(singke) #1
Play_Music(SongList,SongNumber)
SongNumber = SongNumber + 1
#
if Event.type in (QUIT,KEYDOWN,MOUSEBUTTONDOWN):
Graceful_Exit()

Notice that this script imports only the needed functions. The names of the module operations in the
script have been modified to reflect this.


Making the Play List Random


If desired, you can make your script play music from the playlist randomly. Making this happen
requires only a few minor changes. The first change is to import the randinit operation from the
random module, as shown here:


Click here to view code image


from random import randint #Import from Random module

The other two changes are small tweaks to an if statement within the main while loop of the music
script. For the if SongNumber >= MaxSongs: statement, you need to replace SongNumber
= 0 with the statement using the randinit method, as shown here:


Click here to view code image


while True: #Keep playing the Music ############
for Event in event.get():
...
if SongNumber >= MaxSongs:
SongNumber = randint(0,MaxSongs - 1) #Pick random song
Play_Music(SongList,SongNumber)
SongNumber = MaxSongs #Keep songs random
...

Also, to keep the songs playing in a random fashion, instead of incrementing SongNumber after
Play_Music is called, you set it back to being equal to MaxSongs.


Creating a Special Presentation


By now you’ve probably figured out what the “special” presentation is all about: playing music along
with displaying your HD images! There are many reasons you might want to do this. You may have a
special business presentation that needs music behind it. You might want to see images display while
your music is playing. Or, as in this example, you might be a teacher trying to encourage your school
board to buy Raspberry Pis for the students and start up some classes teaching Python.


By-the-Way: Playing One Song Continuously
You might just want to play one loaded song, such as your company’s marketing song,
endlessly during a presentation. To do this, you use the Python statement
pygame.mixer.music.play(-1). The negative one (-1) tells Python to keep
playing the song over and over again, until the script exits.

Basically, this project, shown in Listing 23.5, melds together the HD image presentation script and
the music script. It assumes that both your HD images and your music will be on the same removable

Free download pdf