Skip to content

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

Cart

Prices 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)

Connect buttons to GPIO

About 15 minutes

Wire 4-6 buttons for different sounds.

  1. Place buttons on breadboard.
  2. Connect button 1: one side to GPIO 17, other to GND.
  3. Connect button 2 to GPIO 22.
  4. Connect button 3 to GPIO 23.
  5. Connect button 4 to GPIO 24.
  6. Add more buttons to GPIO 25, 27 if desired.
  7. All buttons share common GND connection.

You should see

All buttons are wired to GPIO pins.

Add sound files

About 10 minutes

Collect music and sound effects.

  1. Create a sounds directory: mkdir ~/musicbox
  2. Download or record sound files (drums, melodies, effects).
  3. Save files as .wav format (best compatibility).
  4. Name them: sound1.wav, sound2.wav, etc.
  5. 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.

  1. Create the script: nano ~/musicbox/musicbox.py
  2. Copy the code below.
  3. Save and exit.
python
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.

  1. Connect speaker or headphones.
  2. Run: python3 ~/musicbox/musicbox.py
  3. Press each button to hear its sound.
  4. 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.