audio_server.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 
3 import rospy
4 import pyaudio
5 import socket
6 import select
7 
8 
9 class AudioServer:
10  def __init__(self):
11  FORMAT = pyaudio.paInt16
12  CHANNELS = 1
13  RATE = 16000
14  CHUNK = 4096
15  self.audio = pyaudio.PyAudio()
16  self.stream = self.audio.open(format=FORMAT, channels=CHANNELS, rate=RATE,
17  input=True, frames_per_buffer=CHUNK,
18  stream_callback=self._callback)
19  self.serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
20  self.read_list = [self.serversocket]
21 
22  self._server_name = rospy.get_param('/dialogflow_client/server_name',
23  '127.0.0.1')
24  self._port = rospy.get_param('/dialogflow_client/port', 4444)
25 
26  rospy.loginfo("DF_CLIENT: Audio Server Started!")
27 
28  def _connect(self):
29  """Create a socket, listen on the server:port and wait for a connection.
30  """
31  self.serversocket.bind((self._server_name, self._port))
32  rospy.loginfo("DF_CLIENT: Waiting for connection...")
33  self.serversocket.listen(1)
34 
35  def _callback(self, in_data, frame_count, time_info, status):
36  """PyAudio callback to continuously get audio data from the mic and put
37  it in a buffer.
38  :param in_data: Audio data received from mic.
39  :return: A tuple with a signal to keep listening to audio input device
40  :rtype: tuple(None, int)
41  """
42  for s in self.read_list[1:]:
43  s.send(in_data)
44  return None, pyaudio.paContinue
45 
46  def start(self):
47  """Main function that attempts to create a socket and establish a
48  connection with a client."""
49  self._connect()
50  try:
51  while True:
52  # select() waits until an object is readable. Here this means
53  # it will wait until there is data to be read from the socket
54  readable, writable, errored = select.select(self.read_list, [], [])
55  for s in readable:
56  if s is self.serversocket:
57  (clientsocket, address) = self.serversocket.accept()
58  self.read_list.append(clientsocket)
59  rospy.loginfo("DF_CLIENT: Connection from {}".format(
60  address))
61  else:
62  data = s.recv(1024)
63  if not data:
64  self.read_list.remove(s)
65  except KeyboardInterrupt as k:
66  rospy.logwarn("DF_CLIENT: Caught Keyboard Interrupt: {}".format(k))
67  except socket.error as e:
68  rospy.logwarn("DF_CLIENT: Caught Socket Error: {}\n "
69  "Restarting...".format(e))
70  self._connect()
71 
72  rospy.loginfo("DF_CLIENT: Finished recording")
73 
74  def __del__(self):
75  self.serversocket.close()
76  # Stop Recording
77  self.stream.stop_stream()
78  self.stream.close()
79  self.audio.terminate()
80 
81 
82 if __name__ == '__main__':
83  rospy.init_node('dialogflow_audio_server')
85  a.start()
def _callback(self, in_data, frame_count, time_info, status)
Definition: audio_server.py:35


dialogflow_ros
Author(s): Anas Abou Allaban
autogenerated on Mon Jun 10 2019 13:02:59