Skip to content

Instantly share code, notes, and snippets.

@HoLengZai
Forked from futurepaul/whynot.py
Created March 15, 2018 07:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HoLengZai/658350463d632ad66e890f649ef1e835 to your computer and use it in GitHub Desktop.
Save HoLengZai/658350463d632ad66e890f649ef1e835 to your computer and use it in GitHub Desktop.
The “Why’d you push that button” button
#Step 1: Import the libraries we need
import pygame.mixer
import RPi.GPIO as GPIO
import glob
import random
import time
#Step 2: Fire up the sound mixer
pygame.mixer.init()
#Step 3: Register the GPIO pin we’ll be observing, and specify that want to “pull up” its voltage
GPIO.setmode(GPIO.BCM)
GPIO.setup(4, GPIO.IN, pull_up_down = GPIO.PUD_UP)
#Step 4: Specify our folder of MP3s
soundfiles = glob.glob(“/home/pi/Desktop/Why-2/*.mp3”)
#Step 5: Here’s our play function!
def play(pin):
print(“playing”)
pygame.mixer.music.load(random.choice(soundfiles))
pygame.mixer.music.play(1)
#Step 6: Print something when the script starts so we know it’s doing something.
print(“ready”)
#Step 7: Actually detect the button press
GPIO.add_event_detect(4, GPIO.FALLING, callback = play, bouncetime = 200)
#Step 8: Loop forever so the program stays alive while waiting for button presses
while 1:
time.sleep(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment