Reputation: 21
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.
Upvotes: 2
Views: 2559
Reputation: 679
This may help you: you can run a query on all audio devices and select the correct one, with the correct settings based on the information it provides, in my case: index 1, and channel 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()
Upvotes: 0