Recording Audio from USB with PyAudio

你离开我真会死。 提交于 2020-02-24 11:40:11

问题


I am trying to record a 5 second clip of audio using a microphone that's connected via usb but I can't seem to get it to work. I am able to record using that mic with QuickTime but not with python. When the script runs, it generates the wave file but the file doesn't have any sound.

This is the code I'm using to record the audio. I have set the input_device_index=4 which is the input device id for my MADIface XT mic.

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

After some more research I have found that it may be a permissions issue with the microphone on PyCharm. I have tried running the script through Terminal where it did ask for permission to use the microphone when I initially ran it but I still have an empty WAV file. I tried also just using the built in microphone but same problems persist.

any help is much appreciated.

来源:https://stackoverflow.com/questions/59774166/recording-audio-from-usb-with-pyaudio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!