使用声音设备录制声音时出错

Error when recording sound with sounddevice

提问人:koegl 提问时间:12/12/2022 最后编辑:koegl 更新时间:1/6/2023 访问量:688

问:

我想使用声音设备来捕获(录制?)从我的扬声器中传出的音频。我的扬声器有两个通道。

这是我的代码(我在这里找到 https://realpython.com/playing-and-recording-sound-python/#python-sounddevice_1):

import sounddevice as sd
from scipy.io.wavfile import write

fs = 44100/2  # Sample rate
seconds = 3  # Duration of recording

myrecording = sd.rec(int(seconds * fs), samplerate=fs, channels=2)
sd.wait()  # Wait until recording is finished
write('output.wav', fs, myrecording)  # Save as WAV file

我收到以下错误:

Traceback (most recent call last):
  File "main.py", line 24, in <module>
    myrecording = sd.rec(int(seconds * fs), samplerate=fs, channels=2)
  File "/usr/local/lib/python3.7/site-packages/sounddevice.py", line 277, in rec
    ctx.input_dtype, callback, blocking, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/sounddevice.py", line 2587, in start_stream
    **kwargs)
  File "/usr/local/lib/python3.7/site-packages/sounddevice.py", line 1422, in __init__
    **_remove_self(locals()))
  File "/usr/local/lib/python3.7/site-packages/sounddevice.py", line 901, in __init__
    f'Error opening {self.__class__.__name__}')
  File "/usr/local/lib/python3.7/site-packages/sounddevice.py", line 2747, in _check
    raise PortAudioError(errormsg, err)
sounddevice.PortAudioError: Error opening InputStream: Invalid number of channels [PaErrorCode -9998]

我在运行 rosetta 模拟 python 的 Mac M1 上。

当我将通道设置为“1”时,它可以工作,但它只能从一个通道录制。

我试图通过运行来获取扬声器的索引,这是输出:print(sd.query_devices())

> 0 MacBook Pro Microphone, Core Audio (1 in, 0 out)
< 1 MacBook Pro Speakers, Core Audio (0 in, 2 out)
  2 Microsoft Teams Audio, Core Audio (2 in, 2 out)

所以我尝试手动设置这个索引,如下所示:

myrecording = sd.rec(int(seconds * fs), samplerate=fs, channels=2, device=1)

但这也产生了同样的错误。

python-sounddevice

评论


答:

0赞 Usr Ustym 1/3/2023 #1

默认情况下,sounddevice 会从输入设备捕获音频。如果要使用来自扬声器的信号,可以尝试将 sd.rec 函数中的参数“device”设置为扬声器的索引。

要查找扬声器的索引,请运行:

print(sd.query_devices())

例如,如果扬声器的索引为 3。Sd.rec 应如下所示:

myrecording = sd.rec(int(seconds * fs), samplerate=fs, channels=2, device=3)

评论

0赞 koegl 1/6/2023
那行不通
0赞 novaXire 1/6/2023
你能添加代码的打印结果吗?print(sd.query_devices())
0赞 Usr Ustym 1/12/2023
尝试使用虚拟电缆