spatialaudio / python-sounddevice

:sound: Play and Record Sound with Python :snake:
https://python-sounddevice.readthedocs.io/
MIT License
1.05k stars 149 forks source link

Script to check if audio is played #248

Open nicolae-stroncea opened 4 years ago

nicolae-stroncea commented 4 years ago

I want to check is I am playing any audio on my PC(music, podcasts, from video, etc).

Here is the script for it:

import sounddevice as sd
import numpy as np

duration = 10
fs = 44100
myrecording = sd.rec(int(duration*fs), samplerate=fs, channels=2)
print(np.count_nonzero(myrecording > 0))

Currently my assumption is that if no audio is playing, then all elements of numpy array will be <=0. Is this correct?

This code is also listening in on the microphone, whilst I strictly want to record audio being played directly from the PC. Is it possible to only check for that?

mgeier commented 4 years ago

Currently my assumption is that if no audio is playing, then all elements of numpy array will be <=0. Is this correct?

Not if you are using an analogue source (e.g. a microphone).

There will be some background noise causing small signal values around 0.

Also, there might be a "DC offset" in your signal.

Typically, one would choose some threshold value to detect "silence".

If you want to check signal values, you shouldn't forget negative values, so you should calculate the absolute signal value before comparing to the threshold.

This code is also listening in on the microphone, whilst I strictly want to record audio being played directly from the PC. Is it possible to only check for that?

It's not straightforward, but depending on your OS you might be able to route all your signals through a "virtual device" which you can then use as input device for the sounddevice module.