使用 pyaudio 的录音无法按预期工作

voice recording using pyaudio not working as expected

这是我编写的用于录制音频的代码,直到我停止程序并将其保存在 output.wav 中。问题是 output.wav 都是无声的,当我打印帧时,它们都是零。我是 运行 它在 Mac OS 上。我尝试使用 Mac 录音机录制音频并且它可以正常工作,所以我想麦克风应该没有问题。为什么会这样?

有什么建议吗?
import pyaudio
import wave

CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100


def record():
    p = pyaudio.PyAudio()

    stream = p.open(format=FORMAT,
                    channels=CHANNELS,
                    rate=RATE,
                    input=True,
                    frames_per_buffer=CHUNK)

    print("Start recording")

    frames = []

    try:
        while True:
            data = stream.read(CHUNK)
            frames.append(data)
    except KeyboardInterrupt:
        print("Done recording")
    except Exception as e:
        print(str(e))

    sample_width = p.get_sample_size(FORMAT)

    stream.stop_stream()
    stream.close()
    p.terminate()

    return sample_width, frames


def record_to_file(file_path):
    wf = wave.open(file_path, 'wb')
    wf.setnchannels(CHANNELS)
    sample_width, frames = record()
    wf.setsampwidth(sample_width)
    wf.setframerate(RATE)
    wf.writeframes(b''.join(frames))
    wf.close()


if __name__ == '__main__':
    print('#' * 80)
    print("Please speak word(s) into the microphone")
    print('Press Ctrl+C to stop the recording')

    record_to_file('output.wav')

    print("Result written to output.wav")
    print('#' * 80)

运行 我的 Windows 10 machine 和 python 3.7 上的这段代码生成了一个音频文件。确保 mac

上的麦克风 enabled