- 1 year ago
Is there a way to detect when a program is reproducing a sound in Python
Yes, it is possible to detect when a program is reproducing a sound in Python. One approach is to use a package such as sounddevice
or pyaudio
to record audio from the default audio input device, and then analyze the audio data to detect sound.
Here's an example code snippet using the sounddevice
package to detect sound:
pythonimport sounddevice as sd
import numpy as np
duration = 5 # duration of recording in seconds
fs = sd.query_devices('default')['default_samplerate']
frames = int(duration * fs)
# Start recording audio
print('Recording...')
audio_data = sd.rec(frames=frames, samplerate=fs, channels=1)
# Wait for recording to complete
sd.wait()
# Analyze audio data to detect sound
if np.max(np.abs(audio_data)) > 0.1:
print('Sound detected!')
else:
print('No sound detected.')
This code records audio from the default audio input device for 5 seconds and then analyzes the audio data to detect sound. If the maximum absolute value of the audio data exceeds a threshold value of 0.1, it is considered to be sound and a message is printed.
Note that this is a simple example and may not be suitable for all use cases. Depending on the specific requirements, you may need to adjust the parameters, the threshold value, or the analysis method to better detect sound in your program.