8b4207db8cb001c3ccb35b9a9f44743fa465889b
[ampy.git] / record.py
1 #!/usr/bin/python3
2 """
3 PyAudio example: Record a few seconds of audio and save to a WAVE
4 file.
5 """
6
7 import pyaudio
8 import wave
9 import sys
10
11 CHUNK = 1024
12 FORMAT = pyaudio.paInt16
13 CHANNELS = 2
14 RATE = 44100
15 RECORD_SECONDS = 5
16 WAVE_OUTPUT_FILENAME = "output.wav"
17 DEVICE = 3
18
19 if sys.platform == 'darwin':
20     CHANNELS = 1
21
22 p = pyaudio.PyAudio()
23
24 stream = p.open(format=FORMAT,
25                 channels=CHANNELS,
26                 rate=RATE,
27                 input=True,
28                 input_device_index=DEVICE,
29                 frames_per_buffer=CHUNK)
30
31 print("* recording")
32
33 frames = []
34
35 for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
36     data = stream.read(CHUNK, exception_on_overflow=False)
37     frames.append(data)
38
39 print("* done recording")
40
41 stream.stop_stream()
42 stream.close()
43 p.terminate()
44
45 wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
46 wf.setnchannels(CHANNELS)
47 wf.setsampwidth(p.get_sample_size(FORMAT))
48 wf.setframerate(RATE)
49 wf.writeframes(b''.join(frames))
50 wf.close()