python 使用PyAudio录制USB音频

5anewei6  于 2023-03-07  发布在  Python
关注(0)|答案(1)|浏览(255)

我试着用一个通过usb连接的麦克风录制一段5秒的音频,但似乎无法正常工作。我可以用那个麦克风用QuickTime录制,但不能用python。当脚本运行时,它会生成一个wave文件,但文件没有任何声音。
这是我用来录制音频的代码。我设置了input_device_index=4,这是我的MADIface XT麦克风的输入设备ID。

import pyaudio
import wave

CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "output.wav"

p = pyaudio.PyAudio()

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

print("* recording")

frames = []

for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
    data = stream.read(CHUNK)
    frames.append(data)

print("* done recording")

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

wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()

经过更多的研究,我发现这可能是PyCharm上的麦克风权限问题。我试着通过终端运行脚本,当我最初运行它时,它确实请求使用麦克风的权限,但我仍然有一个空的WAV文件。我也试着使用内置麦克风,但同样的问题仍然存在。
任何帮助都将不胜感激。

mwg9r5ms

mwg9r5ms1#

这可能会帮助您:您可以在所有音频设备上运行查询,并选择正确的一个,根据它提供的信息进行正确的设置,在我的情况下:索引1和信道1:

def doRecord(duration=10.0):
pyAud = 0
with ignoreStderr():
    pyAud = pyaudio.PyAudio()
foundUSBMic = False
dev_index = -1
for i in range(pyAud.get_device_count()):
    dev = pyAud.get_device_info_by_index(i)
    print((i, dev['name'], dev['maxInputChannels']))
    if dev['name'] == 'USB PnP Sound Device: Audio (hw:1,0)':
        foundUSBMic = True
        dev_index = i 

if foundUSBMic == False or dev_index == -1:
    print("USB MIC NOT FOUND")
    shellESpeak("USB MIC NOT FOUND")

if foundUSBMic:
    form_1 = pyaudio.paInt16  # 16-bit resolution
    chans = 1  # 1 channel
    samp_rate = 44100  # 44.1kHz sampling rate
    chunk = 4096  # 2^12 samples for buffer
    record_secs = int(duration)  # seconds to record
    outputWavFileName = GetThisPath()+'/USBMicRec.wav'  # name of .wav file

    # create pyaudio stream
    stream = pyAud.open(format=form_1, rate=samp_rate, channels=chans,
                    input_device_index=dev_index, input=True,
                    frames_per_buffer=chunk)
    print("recording")
    frames = []

    # loop through stream and append audio chunks to frame array
    for ii in range(0, int((samp_rate/chunk)*record_secs)):
        if stream.is_stopped() == False :
            data = stream.read(chunk)
            frames.append(data)

    # stop the stream, close it, and terminate the pyaudio instantiation

    while stream.is_stopped() == False :
        stream.stop_stream()

    stream.close()
    pyAud.terminate()

相关问题