Funky Music Box
Build a custom music box using Raspberry Pi with button-triggered sound effects and melodies.
- Raspberry Pi
- Beginner
- 45 minutes
- 4 steps
Shop this project
CartPrices from vilros.com. Tax and shipping at checkout.
Before you start, you'll need
- Raspberry Pi (any model)
- 4-6 push buttons
- Breadboard
- Jumper wires
- Speaker or headphones
- Sound files (.wav or .mp3)
Add sound files
About 10 minutes
Collect music and sound effects.
- Create a sounds directory: mkdir ~/musicbox
- Download or record sound files (drums, melodies, effects).
- Save files as .wav format (best compatibility).
- Name them: sound1.wav, sound2.wav, etc.
- Place all sounds in ~/musicbox/.
You should see
Sound files are ready in ~/musicbox/.
Write the music box code
About 15 minutes
Create Python script to map buttons to sounds.
- Create the script: nano ~/musicbox/musicbox.py
- Copy the code below.
- Save and exit.
import pygame
from gpiozero import Button
from signal import pause
pygame.mixer.init()
sounds = {
17: pygame.mixer.Sound('/home/pi/musicbox/sound1.wav'),
22: pygame.mixer.Sound('/home/pi/musicbox/sound2.wav'),
23: pygame.mixer.Sound('/home/pi/musicbox/sound3.wav'),
24: pygame.mixer.Sound('/home/pi/musicbox/sound4.wav'),
}
buttons = {
17: Button(17),
22: Button(22),
23: Button(23),
24: Button(24),
}
def play_sound(pin):
sounds[pin].play()
print(f"Playing sound on pin {pin}")
for pin in buttons.keys():
buttons[pin].when_pressed = lambda p=pin: play_sound(p)
print("Funky Music Box ready!")
print("Press buttons to play sounds.")
pause()Add more buttons and sounds by extending the dictionaries.
You should see
The script is saved.
Test your music box
About 5 minutes
Play sounds with button presses.
- Connect speaker or headphones.
- Run: python3 ~/musicbox/musicbox.py
- Press each button to hear its sound.
- Try pressing multiple buttons in sequence to create rhythms.
You should see
Each button plays its assigned sound.
It didn't work
No sound output.
Check audio output settings. Run: sudo raspi-config → System Options → Audio and select the correct output device.
What to do next
Stuck? Contact Vilros Support with your board model and what you see on screen.