import os import pyaudio import wave def record(dirname, device_id=0, max_recording_time_s=3): print("###################") fname = os.path.join(dirname, "recorded.wav") 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 = max_recording_time_s # seconds to record audio = pyaudio.PyAudio() # create pyaudio instantiation # create pyaudio stream stream = audio.open(format = form_1,rate = samp_rate,channels = chans, \ input_device_index = device_id,input = True, \ frames_per_buffer=chunk) print(f"Recording via microphone for {max_recording_time_s} seconds") frames = [] # loop through stream and append audio chunks to frame array for ii in range(0,int((samp_rate/chunk)*record_secs)): data = stream.read(chunk) frames.append(data) print("Finished recording") # stop the stream, close it, and terminate the pyaudio instantiation stream.stop_stream() stream.close() audio.terminate() # save the audio frames as .wav file wavefile = wave.open(fname,'wb') wavefile.setnchannels(chans) wavefile.setsampwidth(audio.get_sample_size(form_1)) wavefile.setframerate(samp_rate) wavefile.writeframes(b''.join(frames)) wavefile.close() def get_mics(): p = pyaudio.PyAudio() for ii in range(p.get_device_count()): device_name = p.get_device_info_by_index(ii).get('name') print(f"{ii}: {device_name}") if __name__ == "__main__": get_mics() dirname = os.path.dirname(__file__) record(dirname, device_id=0, max_recording_time_s=5)