Advertisement
xrobau

GPIO Trigger Wav on Raspberry PI

Feb 7th, 2022
1,517
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.42 KB | None | 0 0
  1. #!/usr/bin/python3
  2.  
  3. import sys
  4. import signal
  5. import RPi.GPIO as GPIO
  6. import pyaudio
  7. import wave
  8.  
  9. GPIO.setmode(GPIO.BCM)
  10.  
  11. # GPIO 23 (pin 16) & 24 (pin 18) set to HIGH, with both ports should be
  12. # wired to connect to GND on button press. The pins on EITHER SIDE of
  13. # these are GND.
  14. GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_UP)
  15. GPIO.setup(24, GPIO.IN, pull_up_down=GPIO.PUD_UP)
  16.  
  17. # define callback
  18. def callback(in_data, frame_count, time_info, status):
  19.     print ("Callback")
  20.     data = wf.readframes(frame_count)
  21.     return (data, pyaudio.paContinue)
  22.  
  23. def gpio23(channel):
  24.     print ("Pin 16 to ground detected")
  25.  
  26. def gpio24(channel):
  27.     print ("Pin 18 to ground detected")
  28.  
  29. def signal_handler(sig, frame):
  30.     print ("Cleanup")
  31.     GPIO.cleanup()
  32.     sys.exit(0)
  33.  
  34. p = pyaudio.PyAudio()
  35. wf = wave.open('sounda.wav', 'rb')
  36. stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
  37.                 channels=wf.getnchannels(),
  38.                 rate=wf.getframerate(),
  39.                 output=True,
  40.                 stream_callback=callback)
  41.  
  42. # start the sound stream
  43. stream.start_stream()
  44.  
  45. GPIO.add_event_detect(23, GPIO.FALLING, callback=gpio23, bouncetime=300)
  46. GPIO.add_event_detect(24, GPIO.FALLING, callback=gpio24, bouncetime=300)
  47.  
  48. print("Pausing...")
  49. signal.signal(signal.SIGINT, signal_handler)
  50. signal.pause()
  51. print("Here I am")
  52.  
  53. GPIO.cleanup()           # clean up GPIO on normal exit
  54.  
  55.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement