record and store audio in pythn

Solutions on MaxInterview for record and store audio in pythn by the best coders in the world

showing results for - "record and store audio in pythn"
Jameson
18 Mar 2018
1import pyaudio
2import wave
3
4chunk = 1024  # Record in chunks of 1024 samples
5sample_format = pyaudio.paInt16  # 16 bits per sample
6channels = 2
7fs = 44100  # Record at 44100 samples per second
8seconds = 3
9filename = "output.wav"
10
11p = pyaudio.PyAudio()  # Create an interface to PortAudio
12
13print('Recording')
14
15stream = p.open(format=sample_format,
16                channels=channels,
17                rate=fs,
18                frames_per_buffer=chunk,
19                input=True)
20
21frames = []  # Initialize array to store frames
22
23# Store data in chunks for 3 seconds
24for i in range(0, int(fs / chunk * seconds)):
25    data = stream.read(chunk)
26    frames.append(data)
27
28# Stop and close the stream 
29stream.stop_stream()
30stream.close()
31# Terminate the PortAudio interface
32p.terminate()
33
34print('Finished recording')
35
36# Save the recorded data as a WAV file
37wf = wave.open(filename, 'wb')
38wf.setnchannels(channels)
39wf.setsampwidth(p.get_sample_size(sample_format))
40wf.setframerate(fs)
41wf.writeframes(b''.join(frames))
42wf.close()
43