how to record a wav file using python

Solutions on MaxInterview for how to record a wav file using python by the best coders in the world

showing results for - "how to record a wav file using python"
Cassandre
28 Nov 2016
1import pyaudio
2import wave
3
4# the file name output you want to record into
5filename = "recorded.wav"
6# set the chunk size of 1024 samples
7chunk = 1024
8# sample format
9FORMAT = pyaudio.paInt16
10# mono, change to 2 if you want stereo
11channels = 1
12# 44100 samples per second
13sample_rate = 44100
14record_seconds = 5
15# initialize PyAudio object
16p = pyaudio.PyAudio()
17# open stream object as input & output
18stream = p.open(format=FORMAT,
19                channels=channels,
20                rate=sample_rate,
21                input=True,
22                output=True,
23                frames_per_buffer=chunk)
24frames = []
25print("Recording...")
26for i in range(int(44100 / chunk * record_seconds)):
27    data = stream.read(chunk)
28    # if you want to hear your voice while recording
29    # stream.write(data)
30    frames.append(data)
31print("Finished recording.")
32# stop and close stream
33stream.stop_stream()
34stream.close()
35# terminate pyaudio object
36p.terminate()
37# save audio file
38# open the file in 'write bytes' mode
39wf = wave.open(filename, "wb")
40# set the channels
41wf.setnchannels(channels)
42# set the sample format
43wf.setsampwidth(p.get_sample_size(FORMAT))
44# set the sample rate
45wf.setframerate(sample_rate)
46# write the frames as bytes
47wf.writeframes(b"".join(frames))
48# close the file
49wf.close()