Hardware Reference
In-Depth Information
As in previous adventures, you will use Python 3 to create the jukebox controls.
1. Open IDLE 3 by double-clicking the desktop icon or by selecting the application
from the main menu. Click File New Window to open a new text ile.
Alternatively, you could use a command line text editor like nano.
2. In the irst line, as in previous projects using Python, you import the modules
and libraries that you need. For example, the glob module is used for getting a
list of MP3 iles in a directory, the random module is used to shule the MP3
iles inside the list, sys is used for sys.exit and getting command line argu-
ments, and vlc is the Python interface to the vlc library libvlc . Type:
import glob, random, sys, vlc
3. Leave a one-line gap underneath and then type:
if len(sys.argv) <= 1:
print(“Please specify a folder with mp3 files”)
sys.exit(1)
sys.argv is a list that contains the arguments passed to the program on the
command line. You may remember in earlier adventures we accessed programs
from the command line. For instance, if you typed sudo python3 jukebox.
py /home/pi/music into the command line, then the list would contain
jukebox.py at position 0 and /home/pi/music at position 1 (the zero posi-
tion always contains the name of the program that was run). So the irst argu-
ment is at position 1.
4. he next part of the program will load a list of MP3s:
folder = sys.argv[1]
files = glob.glob(folder+”/*.mp3”)
if len(files) == 0:
print(“No mp3 files in directory”, folder, “..exiting”)
sys.exit(1)
As described before, position 1 in sys.argv is the irst command line argu-
ment. he glob function allows you to get a list of iles matching a pattern. he
pattern “*.mp3” expands to any ile which ends in .mp3 , so files = glob.
glob(folder+”/*.mp3” ) will produce a list of all iles ending in .mp3 inside
the folder given on the command line. If the directory contains no MP3s there
won't be anything for the jukebox to play, so you exit early using sys.exit .
5. Now you are able to use the random module to shule the list of MP3 iles to
put them in a random order. Underneath the previous code, type:
random.shuffle(files)
Search WWH ::




Custom Search