Skip to content

Instantly share code, notes, and snippets.

@stevenocchipinti
Last active September 27, 2022 05:31
Show Gist options
  • Save stevenocchipinti/4850742ea81f53574996a48429de4c17 to your computer and use it in GitHub Desktop.
Save stevenocchipinti/4850742ea81f53574996a48429de4c17 to your computer and use it in GitHub Desktop.
Play a random song when a GPIO button is pressed

Play a random song when a GPIO button is pressed

Dependencies for python

sudo pip3 install python-vlc
sudo apt-get install python3-rpi.gpio

Or for python2

sudo pip install python-vlc
sudo apt-get install python-rpi.gpio
#!/use/bin/env python
import RPi.GPIO as GPIO
import vlc
import random
import os
import time
import signal
files_path = os.path.join(os.path.dirname(_file_), "files")
files = os.listdir(files_path)
media_player = vlc.MediaPlayer()
def move_jaw_while_playing(delay=0.5):
time.sleep(delay)
while media_player.is_playing():
print(".", end="", flush = True)
sleep(0.3)
print(";")
def play(filename):
print("Playing file: " + filename)
full_path = os.path.join(os.path.dirname(_file_), filename)
media_player.set_media(vlc.Media(full_path))
media_player.play()
move_jaw_while_playing()
def button_callback(channel):
play("files/" + random.choice(files))
try:
GPIO.setmode(GPIO.BOARD)
GPIO.setup(10, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) # initially pulled low (off)
GPIO.add_event_detect(10, GPIO.RISING, callback=button_callback)
play("boot.mp3")
signal.pause()
except KeyboardInterrupt:
print("Thanks for playing")
finally:
print("Cleaning up...")
GPIO.cleanup()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment