import threading import socket import pyaudio import time # Server settings SERVER_IP = '81.94.159.212' # Replace with your server's IP address DATA_SERVER_PORT = 8012 AUDIO_SERVER_PORT = 65432 # Audio settings FORMAT = pyaudio.paInt16 CHANNELS = 1 RATE = 16000 # Should match the server's expected sample rate CHUNK = 1024 audio = pyaudio.PyAudio() def record_and_send_audio(): while True: try: # Connect to the server to send audio data client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client_socket.connect((SERVER_IP, DATA_SERVER_PORT)) print("Connected to data server") # Initialize PyAudio for recording stream = audio.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK) while True: # Read audio data from the microphone data = stream.read(CHUNK) client_socket.sendall(data) except Exception as e: print(f"Error sending audio: {e}") time.sleep(1) # Wait before retrying finally: # Clean up resources if 'stream' in locals(): stream.stop_stream() stream.close() if 'client_socket' in locals(): client_socket.close() def receive_and_play_audio(): while True: try: # Connect to the server to receive audio data client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client_socket.connect((SERVER_IP, AUDIO_SERVER_PORT)) print("Connected to audio server") # Initialize PyAudio for playback TTS_SAMPLE_RATE = 24000 # Should match the TTS sample rate used on the server stream = audio.open(format=FORMAT, channels=CHANNELS, rate=TTS_SAMPLE_RATE, output=True) while True: # Receive audio data from the server data = client_socket.recv(CHUNK) if not data: raise ConnectionError("Audio server disconnected") # Play the audio data stream.write(data) except Exception as e: print(f"Error receiving audio: {e}") time.sleep(1) # Wait before retrying finally: # Clean up resources if 'stream' in locals(): stream.stop_stream() stream.close() if 'client_socket' in locals(): client_socket.close() def main(): # Start the thread to receive and play audio audio_thread = threading.Thread(target=receive_and_play_audio, daemon=True) audio_thread.start() # Start recording and sending audio while True: record_and_send_audio() print("Reconnecting to data server...") time.sleep(1) if __name__ == '__main__': main()