sender.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. """
  2. This script functions as the sender in a remote microphone streaming setup.
  3. It captures audio from the system's default microphone using pyaudio, encodes this
  4. audio data, and sends it over a WebSocket connection to a server. The server
  5. then relays this data to one or more receivers.
  6. Usage:
  7. Execute the script with Python 3.x to begin capturing and streaming audio.
  8. The script sends audio data to the WebSocket server specified in WS_URL.
  9. If a "panic" message is received from the server, the script stops streaming,
  10. closes the audio stream, and exits.
  11. """
  12. import pyaudio
  13. import websocket
  14. import threading
  15. FORMAT = pyaudio.paInt16
  16. CHANNELS = 1
  17. RATE = 16000
  18. CHUNK = 8000
  19. stream = None
  20. p = pyaudio.PyAudio()
  21. WS_URL = (
  22. "ws://192.168.0.196/ws?password=demopassword"
  23. )
  24. def on_message(ws, message):
  25. print("Received message from server", message)
  26. if message == "panic":
  27. stream.stop_stream()
  28. stream.close()
  29. p.terminate()
  30. print("Terminated")
  31. ws.close()
  32. def on_error(ws, error):
  33. print(error)
  34. def on_open(ws):
  35. def run(*args):
  36. global stream
  37. stream = p.open(
  38. format=FORMAT,
  39. channels=CHANNELS,
  40. rate=RATE,
  41. input=True,
  42. frames_per_buffer=CHUNK,
  43. )
  44. print("Recording...")
  45. while True:
  46. data = stream.read(CHUNK, exception_on_overflow=True)
  47. ws.send(data, opcode=websocket.ABNF.OPCODE_BINARY)
  48. stream.stop_stream()
  49. stream.close()
  50. p.terminate()
  51. print("Terminated")
  52. ws.close()
  53. thread = threading.Thread(target=run)
  54. thread.start()
  55. if __name__ == "__main__":
  56. ws = websocket.WebSocketApp(WS_URL, on_message=on_message, on_error=on_error)
  57. ws.on_open = on_open
  58. ws.run_forever()