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

(singke) #1

You want the playlist file to have the file names of the songs, including their file extension. This way,
you can play different types of music files, such as OGG or WAV. Also, each line of the playlist file
should contain only a single music file name. No directory names are included because they will be
handled in the Python script. The following is a simple example of a play-list that can be used with
this script:


BigBandMusic.ogg
RBMusic.wav
MusicalSong.ogg
...

To open and read your playlist in the Python script, you use the open Python statement. (For a
refresher on opening and reading files, see Hour 11, “Using Files.”)


Watch Out!: Ignoring the End
While PyGame is a wonderful utility for learning how to incorporate various features
into your Python scripts, it can be a little flakey at times, especially when playing
music. For example, PyGame often sporadically ignores the last music file loaded to
play from a playlist. Therefore, you should put your least favorite song last in the
playlist. When you learn how to properly code Python to play music, you can explore
other music library options for Python, if you so desire.

The script opens the playlist and reads it all in, and then it saves the music file information into a list
that the script can use over and over again. (If you need to review the concepts related to lists, see
Hour 8, “Using Lists and Tuples.”)


Each music file name is read from the playlist file and stored into a list called SongList. You need
to strip off the newline character from the end of each read-in record. The .rstrip method will
help you accomplish this. Use the following for loop to read in the music file names from the
playlist after it is opened:


Click here to view code image


for Song in PlayList: #Load PlayList into SongList
#
Song = Song.rstrip('\n') #Strip off newline
if Song != "": #Avoid blank lines in PlayList
Song = MusicDirectory + '/' + Song
SongList.append(Song)
MaxSongs = MaxSongs + 1

Notice that this example uses an if Python statement. This statement allows your script to check for
any blank lines in the playlist file and discard them. It is very easy for blank lines to creep into a file
like this one. This is especially true at the bottom of the file, if you accidently press the Enter key too
many times.


The for loop appends any file names to the end of the SongList list and keeps a count of how
many music files are loaded into the list. Instead of keeping a count, you could also wait until the
SongList list is completely built. Then you can determine how many elements are in the list, using
the Python statement len(SongList).


Controlling the Playback

Free download pdf