test_tools
log_audio.py
Go to the documentation of this file.
1 #!/usr/bin/python
2 
3 from __future__ import print_function
4 
5 import json
6 import os
7 import time
8 import wave
9 from datetime import datetime
10 
11 import pyaudio
12 
13 CHUNK = 1024
14 FORMAT = pyaudio.paInt16
15 CHANNELS = 2
16 RATE = 44100
17 
18 P = pyaudio.PyAudio()
19 
20 RECORDING = False
21 STREAM = P.open(format=FORMAT,
22  channels=CHANNELS,
23  rate=RATE,
24  input=True,
25  frames_per_buffer=CHUNK)
26 
27 
28 def start():
29  global RECORDING
30 
31  if RECORDING:
32  return
33 
34  frames = []
35 
36  print("Starting HMI recording")
37  RECORDING = True
38 
39  last_print = time.time()
40  while RECORDING:
41  data = STREAM.read(CHUNK)
42  frames.append(data)
43  if time.time() - last_print > 1.0:
44  print(".. recording")
45  last_print = time.time()
46 
47  now = datetime.now()
48  wav_filename = "%s/%s.wav" % (STORAGE_FOLDER, now.strftime("%Y-%m-%d-%H-%M-%d-%f"))
49  wf = wave.open(wav_filename, 'wb')
50  wf.setnchannels(CHANNELS)
51  wf.setsampwidth(P.get_sample_size(FORMAT))
52  wf.setframerate(RATE)
53  wf.writeframes(b''.join(frames))
54  wf.close()
55 
56  data = {
57  "wav_filename": wav_filename,
58  }
59 
60  json_filename = "%s/%s.json" % (STORAGE_FOLDER, now.strftime("%Y-%m-%d-%H-%M-%d-%f"))
61  with open(json_filename, 'w') as outfile:
62  json.dump(data, outfile)
63 
64  print("Writing HMI log to %s" % json_filename)
65 
66 
67 def end():
68  global RECORDING
69  RECORDING = False
70 
71 
72 if __name__ == '__main__':
73  STORAGE_FOLDER = os.path.expanduser('/tmp/hmi')
74 
75  if not os.path.exists(STORAGE_FOLDER):
76  os.makedirs(STORAGE_FOLDER)
77 
78  start()
79  time.sleep(10)
80  end()
81 
82  STREAM.stop_stream()
83  STREAM.close()
84  P.terminate()
log_audio.end
def end()
Definition: log_audio.py:67
log_audio.start
def start()
Definition: log_audio.py:28