如何使用 pyaudio 在 macOS 上录制麦克风?

How to record microphone on macos with pyaudio?

我在 python 和 speech_recognition 在 Windows 10 上做了一个简单的语音助手,我也想复制 macOs 的代码。

我下载了 PortAudio 和 PyAudio,代码运行良好,但是当我播放音轨时,我什么也没听到:((当我尝试使用 speech_recognition 时程序没有检测到)
我猜它有权限之类的东西......有人有想法吗?

(我还检查了我使用了正确的设备索引,我确实使用了索引 0(Mackbook 内置麦克风)

这是一些代码示例:

import pyaudio
import wave

chunk = 1024  # Record in chunks of 1024 samples
sample_format = pyaudio.paInt16  # 16 bits per sample
channels = 1
fs = 44100  # Record at 44100 samples per second
seconds = 3
filename = "output.wav"

p = pyaudio.PyAudio()  # Create an interface to PortAudio

print('Recording')

stream = p.open(format=sample_format,
                channels=channels,
                rate=fs,
                frames_per_buffer=chunk,
                input=True)

frames = []  # Initialize array to store frames

# Store data in chunks for 3 seconds
for i in range(0, int(fs / chunk * seconds)):
    data = stream.read(chunk)
    frames.append(data)

# Stop and close the stream 
stream.stop_stream()
stream.close()
# Terminate the PortAudio interface
p.terminate()

print('Finished recording')

# Save the recorded data as a WAV file
wf = wave.open(filename, 'wb')
wf.setnchannels(channels)
wf.setsampwidth(p.get_sample_size(sample_format))
wf.setframerate(fs)
wf.writeframes(b''.join(frames))
wf.close()

我找到了答案!!!

代码实际上一直运行良好,问题是我使用 Visual Studio Code 由于某种原因弄乱了麦克风权限 ‍♂️
现在我 运行 通过终端 python [filename].py 的代码,它工作得很好!