简体   繁体   English

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

[英]How to record microphone on macos with pyaudio?

I made a simple voice assistant in python with speech_recognition on Windows 10 and I wanted to copy the code for macOs too.我在 python 中制作了一个简单的语音助手,在 Windows 10 上使用语音识别功能,我也想复制 macOS 的代码。

I downloaded PortAudio and PyAudio, the code runs fine but when i play the audio track I hear nothing:( (and the program not detect when I try to use the speech_recognition)我下载了 PortAudio 和 PyAudio,代码运行良好,但是当我播放音轨时,我什么也听不见:((当我尝试使用 Speech_recognition 时程序没有检测到)
I guess it something with permissions and things like that... anyone have an idea?我猜它有权限之类的东西......有人有想法吗?

( I also checked I use the right device index and I indeed use index 0 (The Mackbook built-in Microphone) (我还检查了我使用了正确的设备索引,并且确实使用了索引 0(Mackbook 内置麦克风)

here is some code sample:这是一些代码示例:

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()

I found the answer!!!我找到了答案!!!

The code actually worked fine all this time, the problem was that I used Visual Studio Code that for some reason messed up with the microphone permissions ♂️这段代码实际上一直运行良好,问题是我使用了Visual Studio Code ,由于某种原因弄乱了麦克风权限♂️
Now I run the code through terminal with python [filename].py and its working great!现在我通过终端使用python [filename].py运行代码,它工作得很好!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM