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