Introduction: Motion-Triggered Music Player
Turn on music as soon as you walk into a room! This tutorial covers a minimalistic entrance sensor that triggers music of your choice. The design can easily be adapted to suit a variety of needs (e.g. alarm system, motion-triggered lights, etc.).
The system is controlled by a Raspberry Pi, and aside from the RPi and speakers, the materials cost is extremely low (~ $20). Build time is approximately 1 - 2 hours.
For an inexpensive set of speakers, check thrift stores and/or friends' garages.
Step 1: Materials
1. Raspberry Pi + Accessories
This tutorial assumes that the RPi has been set up and includes all necessary accessories (e.g. power cord, SD card, etc.). It is also recommended to use an RPi that has been set up for wireless and with a GPIO breakout cable.
Here's a tutorial on how to set up the RPi.
2. Infrared (IR) Breakbeam Sensor(s)
3. 10 kOhm Resistor
4. Speakers w/ 1/8" audio jack (standard headphone jack)
5. 22 or 24 gauge wire (min. 15 feet)
Recommended to get at least two to three colors (e.g. red, black & yellow).
6. Optional: PCB board and/or Connectors
Although not necessary, a small PCB is recommended to make the system more robust and longer lasting.
Add connectors between the sensor and RPi GPIO for simpler installation, transportation and to more easily allow for future customization.
7. Recommended: LED + 10kOhm Resistor (for testing)
Step 2: Tools
1. Soldering Iron*, Solder & Solder Wick
2. Wire Strippers
3. Epoxy
4. Multimeter
5. Recommended: Breadboard + Breadboard Wires (for setup and testing)
*Note: If you do not have access to a soldering iron, you can twist wires together and coat in hot glue.
Step 3: Setup Raspberry Pi to Play Music
This project provides an overview for how to play a music file saved on the RPi SD card. Possible modifications include setting up the RPi to play music from an external USB drive or streaming music from a website.
1. Install updates.
sudo apt-get update
2. Download example music file for testing.
wget http://goo.gl/MOXGX3 -O example.mp3 --no-check-certificates
Note: This saves the file in whatever directory you are currently in.
3. Open the Terminal window and go into the folder with the music file
Use following command (switch “FolderName” for location of music file):
Cd /home/pi/FolderName
4. Type following command to play file over the audio output:
omxplayer example.mp3
Step 4: Build It! Pt. 1
Recommended to build the circuit on a breadboard and test prior to soldering any of the components onto the PCB board.
1. Extend the wire leads of the IR beam (2 wires: red & black) and IR receiver (3 wires: red, black & yellow).
Plan out and measure the route of the wires from where the IR beam and receiver will be installed to the speaker system. At a minimum, make each wire lead 3 - 5 ft.
Recommended to add connectors to the IR beam and/or receiver to make it easier to disconnect them and, if necessary in the future, modify the system.
If the schematic makes sense, skip the rest of the Build it! steps.
2. Connect the positive side of the IR sensor beam to Raspberry Pi 5V pin.
3. Connect the negative side of the IR beam to RPi ground pin.
4. Connect the positive side of the IR receiver to RPi 5V pin.
5. Connect the negative side of the IR received to the RPi ground pin.
Step 5: Build It! Pt. 2
1. Connect the data pin (yellow wire) of the IR receiver to RPi GPIO pin 23.
2. Connect the 10kOhm resistor between the data pin/RPi GPIO pin 23 and the RPi 5V pin.
3.Recommended: Connect an LED + resistor across the IR receiver data pin (yellow wire).
Connect the positive LED leg to the IR receiver data pin. Connect the negative LED leg to the resistor. Connect the other side of the resistor to ground.
4. Plug in RPi and log in; check that IR beam turns on.
If you've connected the LED, it should turn on when the IR receiver gets the signal from the IR beam. Check that the LED turns off if you interrupt the beam.
Step 6: Code It! Pt. 1
The following is a basic program to play a song when the IR beam signal is broken (AKA when you walk between the IR beam and IR receiver).
Here's a link to the github code.
Save the song of your choice to an easy-to-remember-and-type folder, in this example I used "FolderName" to designate the title of the folder in which the mp3 is saved.
Note: This program prints a message to the screen each time the song is played. This worked for my needs, as I wanted to have a log of each time music is played, but of course this code is just an outline of what is possible. Modify it to suit your needs. Also, please note that the spacing may be off; this is important in Python so be sure to "tabify" your code before running it and check that the spacing is consistent.
#DIY Motion Triggered Music Player
import time
from threading import Thread
import RPi.GPIO as GPIO
import subprocess
class AutoTrigger():
def call_omxplayer(self):
print ("playing " + self.file_path)
pid = subprocess.call(['omxplayer', self.file_path], stderr=subprocess.PIPE, stdout=subprocess.PIPE)
self.is_running = False
def play_song(self):
if not self.is_running:
self.song_thread = Thread(target=self.call_omxplayer, args=())
self.song_thread.start()
self.is_running = True
def __init__(self,pin, file_path):
self.pin = pin
self.file_path = file_path
self.is_running = False
GPIO.setup(pin, GPIO.IN)
'''
This is a hack (the callback) thanks for python closures!
'''
GPIO.add_event_detect(self.pin, GPIO.FALLING, callback=lambda x: self.play_song(), bouncetime=10)
def main(): GPIO.setmode(GPIO.BCM)
AutoTrigger(25, '/home/pi/FolderName/SongName.wav')
AutoTrigger(24, '/home/pi/FolderName/SongName2.mp3')
print ("Ready: !")
try:
while True:
pass
except KeyboardInterrupt:
GPIO.cleanup()
if __name__ == '__main__':
main()
Step 7: Install It!
1. Check system for functionality. If system works as expected, coat all exposed electrical connections (except for RPi plugs) in hot glue or epoxy.
Be aware that epoxy is essentially permanent; use hot glue if you want to modify the system in the future.
2. Attach the IR beam to one side of your front door frame, and the IR receiver on the other side of the door frame, directly in line with the beam. Run the wires up and over the door frame.
It is somewhat tricky to align the IR beam and receiver; highly recommended to use the LED + resistor to quickly see when the beam and receiver are aligned. Use sticky tack or tape to help w/ alignment.
Secure the IR sensor via thumbtacks, nails, screws, etc. Suggested to run the wires up and over the door frame (instead of on the floor).
3. Place the RPi in a convenient and out-of-the-way location.
Consider where you want to place the speakers. If you need longer wires, measure the needed distance and solder in additional wires to the RPi power, ground and GPIO pins.
4. Set up the speakers.
5. Test!
Plug in the RPi and trigger the system to be sure that the music plays when you walk through the IR beam.
Step 8: Activate and Enjoy!
The only issue w/ this design is that the IR receiver range is shorter than I originally wanted, only about 2 feet. Some solutions to this problem would be to use a lens to magnify the IR beam or increase the power input.
Possible modifications of the project include using WiFi to stream music or podcasts, triggering lights, and/or using it to detect motion in and out of your home for a basic security system.. or to see how many times your cat leaves the house while you're gone.
Thanks for reading! Please subscribe and check out my YouTube channel for more projects and other cool science stuff.
Happy building!

Participated in the
Home Automation
13 Comments
Question 2 years ago
How difficult would you say this is for a beginner that has never touched a RPi before? I would love to annoy my family with 'All I Want For Christmas' triggered by a motion sensor but the ONLY computer experience I have is being a very curious and inquisitive Millennial.
Also, I would be building on a RPi 4. Should I search for more updated instructions? I noticed your last comment about the possible code change.
Question 3 years ago
which type of RPi did you use for this setup? Im trying to do something similar with cornhole boards
Answer 3 years ago
Hmm this was awhile ago, so a Raspberry Pi 2 Model B probably? A Pi 4 would be way faster/more powerful, but also the code might have changed? Unsure -- worth a try!
Question 5 years ago on Introduction
I am interested in using this model for a sound installation that I am creating. I would like the sound to turn on when a person enters the gallery and then eventually turn off. Is it possible for the sound to loop for a while? Or would I just make a file that has the sound repeated a number of times? I have previously used an iPod with small speakers but want to have motion triggered sound if possible.
Reply 4 years ago
Yes, you can definitely loop the sound! You can use a for loop to play the song as many times as you want or a while loop that ends after a certain time -- here's a starting guide on those: https://www.pythonforbeginners.com/control-flow-2/...
The for loop might be easier, this would repeat the song 10 times:
for(i in range(10)):
playMusic(goodStuffHere);
i++
Hope that helps! Happy making :D
5 years ago
I did it in a very different way, and I think easier as well. I installed volumio on Rpi and then installed GPIO plugin, this enabled me to play, pause the music if I short GPIO 17 and +5v. I then ordered a normal motion sensor from market, that works on AC, attached a relay to the GPIO. That relay gets triggered by motion, which in turn shorts the GPIO 17 and +5v on Rpi. So as soon as motion is triggered the AC triggers the relay and music starts, the moment after like 2 mins when motion sensor does not detect any motion it triggers the relay again and music pauses. Then again as soon as I enter the room, motion sensor triggers the relay again and music starts from exactly the position it was paused. ....simple yet very effective ... :)
Reply 5 years ago
That's an awesome alternative approach, thanks for sharing!
Question 5 years ago
Is it possible to use an Arduino Uno for this? (I am not an electronic knowledgable person so no hate if it's a stupid question)
Answer 5 years ago
Good question! Yes, you can use an Arduino Uno, but you'll need a different method of hooking up speakers (there's no audio jack input). There might be a shield or you can connect them directly to the digital (analog?) pins. There should be a tutorial somewhere on how to do that..
7 years ago
I'm on a Raspberry pi Model B and the breakbeam works exactly once before I need to reset it and run the py script again. is there any way to reset it after playing the song so that it listens for the break beam trigger again?
Reply 7 years ago
Ah yea there are some funny internal things happening with that media player. Are you using your own code or did you copy mine? That issue should be resolved in my program, although it might be different on different versions of the RPi.
I'd recommend seeing what's going on w/ the OMXplayer, try printing the status as its playing and when its stopped to see how it's handling the song. You can force close it within the program, so try that and see if it fixes the issue.
8 years ago on Introduction
Wow I really love this image
Reply 8 years ago on Introduction
Thank you!