使用 start_stream 时程序不录制音频

Program doesn't record audio when using start_stream

我想在 Python 中使用 PyAudio 录制音频。我正在使用此代码:

import pyaudio
import time

WIDTH = 2
CHANNELS = 2
RATE = 44100

p = pyaudio.PyAudio()

def callback(in_data, frame_count, time_info, status):
    return (in_data, pyaudio.paContinue)

stream = p.open(format=p.get_format_from_width(WIDTH),
                channels=CHANNELS,
                rate=RATE,
                input=True,
                output=True,
                stream_callback=callback)

stream.start_stream()

while stream.is_active():
    time.sleep(0.1)

stream.stop_stream()
stream.close()

p.terminate()

它不录制和播放音频,但以错误结束。如果我从控制台 运行 它,它会打印:

jack server is not running or cannot be started

完整输出在这里:https://pastebin.com/JR5ADT3p

我该怎么办?

试试这个:

def record(duration=3, fs=8000):
    nsamples = duration*fs
    p = pyaudio.PyAudio()
    stream = p.open(format=pyaudio.paInt16, channels=1, rate=fs, input=True,
                    frames_per_buffer=nsamples)
    buffer = stream.read(nsamples)
    array = np.frombuffer(buffer, dtype='int16')
    stream.stop_stream()
    stream.close()
    p.terminate()
    return array

my_recordvoice = record() # say something