Added note about cgroup2 protection
[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 json
8 import sys
9 import wave
10
11 import pyaudio
12
13 PARAMFILE = '/var/lib/ampy/params.json'
14 CHUNK = 1024
15 FORMAT = pyaudio.paInt16
16 CHANNELS = 2
17 RATE = 44100
18 RECORD_SECONDS = 5
19 WAVE_OUTPUT_FILENAME = "/tmp/output.wav"
20
21 if sys.platform == 'darwin':
22     CHANNELS = 1
23
24 p = pyaudio.PyAudio()
25
26 try:
27     with open(PARAMFILE) as f:
28         params = json.loads(f.read())
29         alsadevice = params['alsadevice']
30 except (FileNotFoundError, json.decoder.JSONDecodeError, KeyError):
31     print("Error reading the parameters. Please run device.py")
32
33 stream = p.open(format=FORMAT,
34                 channels=CHANNELS,
35                 rate=RATE,
36                 input=True,
37                 input_device_index=alsadevice,
38                 frames_per_buffer=CHUNK)
39
40 print("* recording to", WAVE_OUTPUT_FILENAME)
41
42 frames = []
43
44 for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
45     data = stream.read(CHUNK, exception_on_overflow=False)
46     frames.append(data)
47
48 print("* done recording")
49
50 stream.stop_stream()
51 stream.close()
52 p.terminate()
53
54 wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
55 wf.setnchannels(CHANNELS)
56 wf.setsampwidth(p.get_sample_size(FORMAT))
57 wf.setframerate(RATE)
58 wf.writeframes(b''.join(frames))
59 wf.close()