Clean up duplicate php code to inc file
[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 sys
8 import wave
9
10 import pyaudio
11
12 CHUNK = 1024
13 FORMAT = pyaudio.paInt16
14 CHANNELS = 2
15 RATE = 44100
16 RECORD_SECONDS = 5
17 WAVE_OUTPUT_FILENAME = "output.wav"
18 DEVICE = 5
19
20 if sys.platform == 'darwin':
21     CHANNELS = 1
22
23 p = pyaudio.PyAudio()
24
25 stream = p.open(format=FORMAT,
26                 channels=CHANNELS,
27                 rate=RATE,
28                 input=True,
29                 input_device_index=DEVICE,
30                 frames_per_buffer=CHUNK)
31
32 print("* recording")
33
34 frames = []
35
36 for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
37     data = stream.read(CHUNK, exception_on_overflow=False)
38     frames.append(data)
39
40 print("* done recording")
41
42 stream.stop_stream()
43 stream.close()
44 p.terminate()
45
46 wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
47 wf.setnchannels(CHANNELS)
48 wf.setsampwidth(p.get_sample_size(FORMAT))
49 wf.setframerate(RATE)
50 wf.writeframes(b''.join(frames))
51 wf.close()