我已经工作了几个小时,试图找到一种无需麦克风即可测量应用程序音量的方法。
我首先尝试使用PyAudio,但所有示例都是使用麦克风作为捕获来自扬声器的声音的设备,但是由于我没有麦克风,所以这变得很困难。
然后我找到了python-sounddevice,它似乎应该可以工作,但是尝试获取声音时却不断出错。
这是我使用的代码:
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)
我打印了设备,所以我将在这里打印它们:
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)
这是我得到的错误:
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]
也许我采用了错误的方式,通道为0 in 2 out,我尝试将其作为默认值。