# Program pa_record.py to record with a microphone import os, pyaudio, re, wave from sys import exit # # Start PyAudio pa = pyaudio.PyAudio() # PyAudio instance os.system('clear') # clean the screen try: did = pa.get_default_input_device_info() except: print("Sorry, I cannot find any microphone!\n") pa.terminate() # stop PyAudio raise dha = pa.get_default_host_api_info() # # Set parameters spr = int(did['defaultSampleRate']) # may try spr=16000 chs = 2 ; mod = "stereo" if did['maxInputChannels']==1: chs = 1 ; mod = "mono" fmt = pyaudio.paInt16 # 16 bit resolution # # Definition of variables chk = 4096 # 2^12 samples for buffer sec = 5.0 # desired recording time in s n = int( (spr/chk) * sec ) + 1 # round up the duration dur = (n * chk) / spr fil = "voice.wav" # path to output audio file frames = [] # # Print info print(__file__) print("audio recording with a microphone") print("input device:", did['name']+",",mod) print("host api (sound server):",dha['name']) print("sample format: paInt16 (16 bit)") print("duration of audio recording:",round(dur,1),"s") # # Recording input("\nPress ENTER to start recording!") stream = pa.open( rate = spr, # sampling rate channels = chs, # number of channels format = fmt, # sampling size and format input = True, # this is an input stream input_device_index = None, # uses default device frames_per_buffer = chk, # frame number per buffer ) for i in range(0, n): data = stream.read(chk,exception_on_overflow=False) frames.append(data) stream.stop_stream() stream.close() # # Stop PyAudio pa.terminate() # # Save recorded data in WAV file wf = wave.open(fil,"wb") wf.setnchannels(chs) wf.setsampwidth(pa.get_sample_size(fmt)) wf.setframerate(spr) wf.writeframes(b''.join(frames)) wf.close() print("\nthe audio file",fil,"was written,") print("you may play it with: aplay",fil,"\n")