I have been working some hours now trying to figure out a way to measure sound volume from an application without having a microphone.
I first tried with PyAudio but all examples is with using a microphone as capturing device for the sound from the speakers, but as I do not own a microphone this becomes hard.
Then I found python-sounddevice and it seems like it should work, but I keep getting errors trying to fetch the sound.
Here is the code I use:
import sounddevice as sd
import numpy as np
duration = 10
print("___________")
print("Devices:\n" + str(sd.query_devices()))
sd.default.device = [1, 1]
sd.default.channels = [0, 2]
print("___________")
def print_sound(indata, outdata, frames, time, status):
volume_norm = np.linalg.norm(indata)*10
print(int(volume_norm))
with sd.Stream(callback=print_sound):
sd.sleep(duration * 1000)
I print the devices so I will print them here:
Devices:
0 Microsoft Sound Mapper - Output, MME (0 in, 2 out)
< 1 Högtalare (High Definition Audi, MME (0 in, 2 out)
2 Primär ljuddrivrutin, Windows DirectSound (0 in, 2 out)
3 Högtalare (High Definition Audio Device), Windows DirectSound (0 in, 2 out)
4 Högtalare (High Definition Audio Device), Windows WASAPI (0 in, 2 out)
5 SPDIF Out (HD Audio SPDIF out 2), Windows WDM-KS (0 in, 2 out)
6 SPDIF Out (HD Audio SPDIF out), Windows WDM-KS (0 in, 2 out)
7 Speakers (HD Audio Speaker), Windows WDM-KS (0 in, 6 out)
And this is the error I get:
Traceback (most recent call last):
File "sound_handler.py", line 17, in <module>
with sd.Stream(callback=print_sound):
File "C:\Users\breid\AppData\Local\Programs\Python\Python36\lib\site-packages\sounddevice.py", line 1662, in __init__
**_remove_self(locals()))
File "C:\Users\breid\AppData\Local\Programs\Python\Python36\lib\site-packages\sounddevice.py", line 780, in __init__
'Error opening {0}'.format(self.__class__.__name__))
File "C:\Users\breid\AppData\Local\Programs\Python\Python36\lib\site-packages\sounddevice.py", line 2572, in _check
raise PortAudioError(errormsg, err)
sounddevice.PortAudioError: Error opening Stream: Invalid number of channels [PaErrorCode -9998]
Maybe I am approching this the wrong way, The channels is 0 in 2 out and I tries that as default.