#!/usr/bin/python3 # Tonaufnahme mit einem USB-Mikrophon -> WAV-Audiodatei import pyaudio, re, wave from sys import exit # Start of PyAudio pa = pyaudio.PyAudio() # pyaudio.PyAudio instance # Definition of variables chk = 4096 # 2^12 samples for buffer fil = "test.wav" # path to output audio file frames = [] # list of audio chunks ndv = 0 # number of USB Audio cards re1 = re.compile(r"hw:\d,\d") # reg.expr. for ALSA cards re2 = re.compile(r"USB.*Audio \(hw:(\d),\d") # reg.expr. res = pyaudio.paInt16 # 16 bit resolution sec = 3 # recording time in seconds dsr = "defaultSampleRate" # (16000, 44100, 48000) spr = int(pa.get_device_info_by_index(2)[dsr]) chs = 1 # number of channels # Information to the user pa = pyaudio.PyAudio() # pyaudio.PyAudio instance print("\nIgnore the above messages from alsa-lib!") print("\nALSA audio devices\n------------------") for i in range(pa.get_device_count()): dvi = pa.get_device_info_by_index(i).get('name') if re1.search(dvi): print(dvi) mch = re2.search(dvi) if mch: ndv = ndv + 1 dev = mch.group(1) if ndv != 1: pa.terminate() exit("\nError in selecting USB sound card!\n") print("\nWe will use ALSA sound card "+dev+".") print("The sampling rate is", spr, "Hz.") print("The duration of recording is", sec, "s.") #!/usr/bin/python3 # Definition of audio stream stream = pa.open( format = res, rate = spr, channels = chs, input_device_index = int(dev), input = True, frames_per_buffer = chk, ) # Recording (append audio chunks to frame list) n = int( (spr/chk) * sec ) t = str( round(n*chk/spr,1) ) input("Press ENTER to start recording!") print("\nRECORDING", end=" ") print("("+t+" s, "+str(n)+" chunks)", end=" ") for i in range(0, n): data = stream.read(chk, exception_on_overflow = False) frames.append(data) # Stop of PyAudio stream.stop_stream() stream.close() pa.terminate() print("finished.") # Save record to output audio file (WAV format) out = wave.open(fil,"wb") out.setnchannels(chs) out.setsampwidth(pa.get_sample_size(res)) out.setframerate(spr) out.writeframes(b''.join(frames)) out.close() print("Audio file",fil,"written.\n")