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

(singke) #1

Feel free to add as many changes as you desire. This is your HD image presentation script!


Playing Music


You can use Python to create some creative scripts for playing your music—for free! After you create
such a script, you can take your Pi over to someone else’s place, hook it up to their television, and
listen to your favorite music. The best part is that you’re the one writing the script playing the music!


Creating a Basic Music Script


To keep your music script simple, you will continue to use the PyGame library you’ve already
learned about. PyGame does a decent job of handling music. You might think that the best way to
handle music files would be to create a Sound object, as you did in Hour 19 for the Python game.
That does, in fact, work, but loading the music files into Python this way goes very slowly. Thus, it’s
best to avoid using the Sound object to play music.


By-the-Way: Other Modules and Packages for Playing Music
There are several other modules and packages for Python that you can use to create
scripts for playing music files. A rather detailed list of them is shown at
http://wiki.python.org/moin/PythonInMusic.

Besides doing the basic PyGame initialization, you primarily need to use two methods in this script:
pygame.mixer.music.load and pygame.mixer.music.play. Each music file must be
loaded from the disk into the Python script, before it can be played. Here’s an example of loading a
music file:


Click here to view code image


pygame.mixer.music.load('/home/pi/music/BigBandMusic.ogg')

Did You Know: Problems with MP3 Formats
Music comes in several standard file formats. Three of the most popular are MP3,
WAV, and OGG. However, you need to be aware that the MP3 file format is a closed-
source format, so the open-source world typically frowns on it.
Python and PyGame can handle MP3 file format, but be aware that MP3 files may not
play on your Linux system and can even cause the system to crash. It is best to use
either uncompressed music files, such as the WAV format, or open-source compressed
files such as OGG files. You can convert your MP3 music files to supported formats
by using either online conversion websites or locally installed software tools. You can
find a list of many audio file conversion tools at
http://wiki.python.org/moin/PythonInMusic.

After a music file is loaded, you use the play method for playing the file, as shown here:


pygame.mixer.music.play(0)

The number shown here, 0 , is the number of times the music file will play. You might think that zero
means it will play zero times, but actually, when the play method sees 0 , it plays the file one time

Free download pdf