I am looking for a solution that detects sound and sets GPIO21 to low and GPIO21 to high, after 5 minutes when there is no sound. I need it for a streamer (Raspberry Pi) that will run shairport-sync, tidal-connect and spotify. When sound is detected, GPIO should trigger my amplifier. Unfortunately I can not code python, so I hope someone can help
2 Answers
I think you might find this link helpful: Detecting audio. You shouldn't need all of the code in that answer, just the part on detecting silence.
I believe you can use the python gpiozero library for using the GPIO ports. You should be able to treat it as an LED.
import gpiozero #For GPIO
import time #To sleep
###REPLACE THIS WITH YOUR OWN FUNCTION (Like the one I posted in the above link)###
def is_silent():
return True
pin = gpiozero.LED(21) #Set up the GPIO pin
pin.on() #Turn it on
seconds_since_sound = 300 #Set seconds since last sound to high
while(True):
if(is_silent): #Check if there is no sounds
if(seconds_since_sound >= 300): #If there is no sounds and it has been more than 5 mins since the last sound
pin.on() #Turn on
else:
seconds_since_sound += 1 #Otherwise increment by a second
time.sleep(1) #Sleep for a second
else:
seconds_since_sound = 0 #If there is a sound then set timer to 0
pin.off() #Turn off
Unfortunately I am unable to test if the code works as I do not have access to a raspberry pi.
It looks like the silence detection does not work in python 3.
EDIT:
It looks like you can record the soundcard on some devices using this line of code:
import pyaudio #import pyaudio
p = pyaudio.PyAudio() #setup pyaudio
stream = p.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, output=True, frames_per_buffer=CHUNK_SIZE, input_device_index=2) #open pyaudio stream
snd_data = array('h', stream.read(CHUNK_SIZE)) #Capture data (should be done in while loop)
return (max(snd_data) > threshold) #Check if data is louder than threshold
(Change the input device index to point to the output of your sound card)
Once again, I am unable to test if this works as it only runs of python 2. It uses pyaudio.

- 21
- 6
-
Thanks for your reply. Unfortunately, it does not work. There is no error and the GPIO part is correct. It just detects no sound, unfortunately. – JanLP Nov 21 '21 at 02:06
-
Does your raspberry pi definitely come with a microphone and what version of python are your running? – SolveItPlanet Nov 21 '21 at 12:08
@SolveltPlanet
It is disabled via #dtparam=audio=on
and I have Python 2.7.16 installed. Here is aplay -l
**** List of PLAYBACK Hardware Devices ****
card 1: AUDIO [SMSL USB AUDIO], device 0: USB Audio [USB Audio]
Subdevices: 0/1
Subdevice #0: subdevice #0

- 1