Created
January 31, 2024 14:30
-
-
Save nikola-j/cde1a7eff28d75b03f79a810e9999819 to your computer and use it in GitHub Desktop.
RPI White noise + Airplay server
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Simple script to start white noise on button click on rpi zero w2 combined with waveshare WM8960 audio hat | |
# It will also stop/start an airplay container | |
import RPi.GPIO as GPIO | |
import pygame | |
import time | |
import subprocess | |
# Initialize pygame mixer | |
pygame.mixer.init() | |
# Load white noise sound | |
white_noise = pygame.mixer.Sound('/home/pi/Documents/white_noise/white_noise.wav') | |
white_noise.set_volume(0.3) | |
# GPIO setup | |
BUTTON_PIN = 17 | |
GPIO.setmode(GPIO.BCM) | |
GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) | |
# Airplay server docker container name | |
docker_name = 'nifty_nash' | |
playing = False | |
def start_container(): | |
try: | |
subprocess.run(['docker', 'start', docker_name], check=True) | |
except subprocess.CalledProcessError as e: | |
print(f"Failed to start Docker container: {e}") | |
def stop_container(): | |
try: | |
subprocess.run(['docker', 'stop', docker_name], check=True) | |
except subprocess.CalledProcessError as e: | |
print(f"Failed to stop Docker container: {e}") | |
def play_white_noise(): | |
global playing | |
if not playing: | |
stop_container() | |
white_noise.play(-1) # Play indefinitely | |
playing = True | |
def stop_white_noise(): | |
global playing | |
if playing: | |
start_container() | |
white_noise.stop() | |
playing = False | |
def button_callback(channel): | |
global playing | |
if playing: | |
print("STOPPPING WHITE NOISE") | |
stop_white_noise() | |
else: | |
print("STARTING WHITE NOISE") | |
play_white_noise() | |
# Add event detection for button press | |
GPIO.add_event_detect(BUTTON_PIN, GPIO.FALLING, callback=button_callback, bouncetime=500) | |
try: | |
while True: | |
time.sleep(0.1) # Keep the script running | |
except KeyboardInterrupt: | |
print("Script terminated by user") | |
finally: | |
GPIO.cleanup() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment