Adding Music to Code On Your Raspberry Pi
So as I prepare for next week, coaching with some other great folks with the Oracle Education Foundation using the Raspberry Pi, I wanted to add some fun music into my code to work with our motor mascot project. To do so, you need a few things:
- A small speaker with a 3.5 plugin to the Raspberry Pi. I have a small, round, rechargeable one that I love.
- Have an FM radio station that streams music that you can use in your code.
- Install and use music libraries
If you haven’t done so recently, run an update on your Rpi:
sudo apt-get update
Now that you know your Rpi is up to date, let’s get the MPlayer software:
sudo apt-get install mplayer mplayer-gui alsa-base alsa-utils pulseaudio mpg123
If you have your Rpi hooked into a small monitor, like I do, then don’t be surprised if the mplayer application fails due to the display constraints. The rest of the code and librariesiare what we’re really interested in, so not a big deal.
Once it’s finished, reboot your Rpi:
sudo reboot
Once it’s up, lets do a bit of code. There are a number of online FM URL’s that can be used with the mplayer, so it’s really a lot of fun. You must have WiFi access configured on your Rpi for this to run:
import system
os.system(“mplayer -playlist http://tunein.com/radio/1FM—Absolute-Top-40-s48967/”)
Save the file as play_music.py
To run this, simply type in:
sudo python3 play_music.py
I’ve updated my script to do a few things, including blinking lights and spinning motors, but the video gives you at least a taste of the motor and the music!
Have a great Firday, folks!