用sounddevice录制声音时出错



我想使用sounddevice来捕获(记录?)来自扬声器的音频。我的扬声器有两个声道。

这是我的代码(我在这里找到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]

我在Mac M1上运行rosetta仿真python。

当我将通道设置为'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)

但是这也会产生同样的错误。

默认情况下,sounddevice从输入设备捕获音频。如果你想使用扬声器的信号,你可以尝试用sd设置参数'device'。Rec函数到您的扬声器索引。

查找扬声器的索引:

print(sd.query_devices())

例如,如果你的演讲者的索引是3。Sd。Rec应该看起来像:

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

相关内容

  • 没有找到相关文章

最新更新