audio_test.py
Go to the documentation of this file.
1 # Copyright 2017 Mycroft AI Inc.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 #
15 import argparse
16 import os
17 import pyaudio
18 from contextlib import contextmanager
19 
20 from speech_recognition import Recognizer
21 
22 from mycroft.client.speech.mic import MutableMicrophone
23 from mycroft.configuration import Configuration
24 from mycroft.util import play_wav
25 from mycroft.util.log import LOG
26 import logging
27 
28 """
29 Audio Test
30 A tool for recording X seconds of audio, and then playing them back. Useful
31 for testing hardware, and ensures
32 compatibility with mycroft recognizer loop code.
33 """
34 
35 # Reduce loglevel
36 LOG.level = 'ERROR'
37 logging.getLogger('urllib3').setLevel(logging.WARNING)
38 
39 
40 @contextmanager
42  """ Context manager blocking stdout and stderr completely.
43 
44  Redirects stdout and stderr to dev-null and restores them on exit.
45  """
46  # Open a pair of null files
47  null_fds = [os.open(os.devnull, os.O_RDWR) for i in range(2)]
48  # Save the actual stdout (1) and stderr (2) file descriptors.
49  orig_fds = [os.dup(1), os.dup(2)]
50  # Assign the null pointers to stdout and stderr.
51  os.dup2(null_fds[0], 1)
52  os.dup2(null_fds[1], 2)
53  try:
54  yield
55  finally:
56  # Re-assign the real stdout/stderr back to (1) and (2)
57  os.dup2(orig_fds[0], 1)
58  os.dup2(orig_fds[1], 2)
59  for fd in null_fds + orig_fds:
60  os.close(fd)
61 
62 
63 def record(filename, duration):
64  mic = MutableMicrophone()
65  recognizer = Recognizer()
66  with mic as source:
67  audio = recognizer.record(source, duration=duration)
68  with open(filename, 'wb') as f:
69  f.write(audio.get_wav_data())
70 
71 
72 def main():
73  parser = argparse.ArgumentParser()
74  parser.add_argument(
75  '-f', '--filename', dest='filename', default="/tmp/test.wav",
76  help="Filename for saved audio (Default: /tmp/test.wav)")
77  parser.add_argument(
78  '-d', '--duration', dest='duration', type=int, default=10,
79  help="Duration of recording in seconds (Default: 10)")
80  parser.add_argument(
81  '-v', '--verbose', dest='verbose', action='store_true', default=False,
82  help="Add extra output regarding the recording")
83  parser.add_argument(
84  '-l', '--list', dest='show_devices', action='store_true',
85  default=False, help="List all availabile input devices")
86  args = parser.parse_args()
87 
88  if args.show_devices:
89  print(" Initializing... ")
90  pa = pyaudio.PyAudio()
91 
92  print(" ====================== Audio Devices ======================")
93  print(" Index Device Name")
94  for device_index in range(pa.get_device_count()):
95  dev = pa.get_device_info_by_index(device_index)
96  if dev['maxInputChannels'] > 0:
97  print(' {}: {}'.format(device_index, dev['name']))
98  print()
99 
100  config = Configuration.get()
101  if "device_name" in config["listener"]:
102  dev = config["listener"]["device_name"]
103  elif "device_index" in config["listener"]:
104  dev = "Device at index {}".format(config["listener"]["device_index"])
105  else:
106  dev = "Default device"
107  samplerate = config["listener"]["sample_rate"]
108  play_cmd = config["play_wav_cmdline"].replace("%1", "WAV_FILE")
109  print(" ========================== Info ===========================")
110  print(" Input device: {} @ Sample rate: {} Hz".format(dev, samplerate))
111  print(" Playback commandline: {}".format(play_cmd))
112  print()
113  print(" ===========================================================")
114  print(" == STARTING TO RECORD, MAKE SOME NOISE! ==")
115  print(" ===========================================================")
116 
117  if not args.verbose:
118  with mute_output():
119  record(args.filename, args.duration)
120  else:
121  record(args.filename, args.duration)
122 
123  print(" ===========================================================")
124  print(" == DONE RECORDING, PLAYING BACK... ==")
125  print(" ===========================================================")
126  status = play_wav(args.filename).wait()
127  if status:
128  print('An error occured while playing back audio ({})'.format(status))
129 
130 
131 if __name__ == "__main__":
132  main()
def record(filename, duration)
Definition: audio_test.py:63


mycroft_ros
Author(s):
autogenerated on Mon Apr 26 2021 02:35:40