receiver.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. """
  2. This script is the receiver component of a remote microphone streaming system.
  3. It connects to a specified WebSocket server, receives audio data streamed from a sender,
  4. and plays it back in real-time. It uses pyaudio for audio playback and numpy for
  5. manipulation of the audio data.
  6. Usage:
  7. Run the script with Python 3.x. It will automatically connect to the WebSocket server
  8. specified in the WS_URL variable and start playing received audio data.
  9. To stop the script, focus on the terminal and press Ctrl+C.
  10. """
  11. import pyaudio
  12. import websocket
  13. import threading
  14. import numpy as np
  15. # Audio configuration
  16. FORMAT = pyaudio.paInt16
  17. CHANNELS = 1
  18. RATE = 44100
  19. CHUNK = 1024 * 10
  20. # WebSocket
  21. WS_URL = (
  22. "ws://audioendpoint.yourserver.com/ws?password=demopassword"
  23. )
  24. def on_message(ws, message):
  25. # Convert the message data to a numpy array of the correct type
  26. data = np.frombuffer(message, dtype=np.int16)
  27. stream.write(data.tobytes())
  28. def on_error(ws, error):
  29. print(error)
  30. def on_open(ws):
  31. print("Opened connection")
  32. def send_panic_and_exit():
  33. print("Panic! Sending 'panic' message...")
  34. ws.send("panic")
  35. ws.close()
  36. stream.stop_stream()
  37. stream.close()
  38. p.terminate()
  39. print("Terminated. Exiting.")
  40. exit()
  41. if __name__ == "__main__":
  42. ws = websocket.WebSocketApp(
  43. WS_URL, on_message=on_message, on_error=on_error
  44. )
  45. p = pyaudio.PyAudio()
  46. stream = p.open(
  47. format=FORMAT,
  48. channels=CHANNELS,
  49. rate=RATE,
  50. output=True,
  51. frames_per_buffer=CHUNK,
  52. )
  53. wst = threading.Thread(target=lambda: ws.run_forever())
  54. wst.daemon = True
  55. wst.start()
  56. print("Receiving... Press Ctrl+C to stop")
  57. try:
  58. while True:
  59. pass # Keep the main thread alive
  60. except KeyboardInterrupt:
  61. send_panic_and_exit()