|
| 1 | +import socket |
| 2 | +import threading |
| 3 | +from queue import Queue |
| 4 | +from dataclasses import dataclass, field |
| 5 | +import soundfile as sf |
| 6 | +import numpy as np |
| 7 | +import struct |
| 8 | +import pickle |
| 9 | + |
| 10 | +@dataclass |
| 11 | +class ListenAndPlayArguments: |
| 12 | + send_rate: int = field(default=16000, metadata={"help": "In Hz. Default is 16000."}) |
| 13 | + recv_rate: int = field(default=16000, metadata={"help": "In Hz. Default is 16000."}) |
| 14 | + list_play_chunk_size: int = field( |
| 15 | + default=512, |
| 16 | + metadata={"help": "The size of data chunks (in bytes). Default is 512."}, |
| 17 | + ) |
| 18 | + host: str = field( |
| 19 | + default="localhost", |
| 20 | + metadata={ |
| 21 | + "help": "The hostname or IP address for listening and playing. Default is 'localhost'." |
| 22 | + }, |
| 23 | + ) |
| 24 | + send_port: int = field( |
| 25 | + default=12345, |
| 26 | + metadata={"help": "The network port for sending data. Default is 12345."}, |
| 27 | + ) |
| 28 | + recv_port: int = field( |
| 29 | + default=12346, |
| 30 | + metadata={"help": "The network port for receiving data. Default is 12346."}, |
| 31 | + ) |
| 32 | + input_audio_file: str = field( |
| 33 | + default="sample_audio.wav", |
| 34 | + metadata={"help": "Path to the audio file to use as input."}, |
| 35 | + ) |
| 36 | + |
| 37 | + |
| 38 | +def listen_and_dont_play( |
| 39 | + send_rate=16000, |
| 40 | + recv_rate=16000, |
| 41 | + list_play_chunk_size=512, |
| 42 | + host="localhost", |
| 43 | + send_port=12345, |
| 44 | + recv_port=12346, |
| 45 | + input_audio_file="sample_audio.wav", |
| 46 | +): |
| 47 | + send_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 48 | + send_socket.connect((host, send_port)) |
| 49 | + |
| 50 | + recv_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 51 | + recv_socket.connect((host, recv_port)) |
| 52 | + |
| 53 | + print(f"Simulating recording and streaming using {input_audio_file}...") |
| 54 | + |
| 55 | + stop_event = threading.Event() |
| 56 | + recv_queue = Queue() |
| 57 | + send_queue = Queue() |
| 58 | + |
| 59 | + def load_audio_chunks(file_path, chunk_size, sample_rate, append_silence_secs=5): |
| 60 | + """Load audio file, append silence, and yield chunks of audio data.""" |
| 61 | + # Read audio file |
| 62 | + audio_data, audio_sample_rate = sf.read(file_path, dtype='int16') |
| 63 | + if audio_sample_rate != sample_rate: |
| 64 | + raise ValueError(f"Expected sample rate of {sample_rate}, but got {audio_sample_rate}") |
| 65 | + |
| 66 | + # Calculate and append 5 seconds of silence |
| 67 | + silence = np.zeros(int(sample_rate * append_silence_secs), dtype='int16') |
| 68 | + combined_audio = np.concatenate([audio_data, silence]) |
| 69 | + |
| 70 | + # Break audio into chunks |
| 71 | + for i in range(0, len(combined_audio), chunk_size): |
| 72 | + yield combined_audio[i:i + chunk_size].tobytes() |
| 73 | + |
| 74 | + def send(stop_event, send_queue): |
| 75 | + for chunk in load_audio_chunks(input_audio_file, list_play_chunk_size, send_rate): |
| 76 | + if stop_event.is_set(): |
| 77 | + break |
| 78 | + send_queue.put(chunk) |
| 79 | + |
| 80 | + send_queue.put(b"END") |
| 81 | + |
| 82 | + def recv(stop_event, recv_queue): |
| 83 | + def receive_full_chunk(conn, chunk_size): |
| 84 | + data = b"" |
| 85 | + while len(data) < chunk_size: |
| 86 | + packet = conn.recv(chunk_size - len(data)) |
| 87 | + if not packet: |
| 88 | + return None # Connection has been closed |
| 89 | + data += packet |
| 90 | + return data |
| 91 | + |
| 92 | + while not stop_event.is_set(): |
| 93 | + # Step 1: Receive the first 4 bytes to get the packet length |
| 94 | + length_data = receive_full_chunk(recv_socket, 4) |
| 95 | + if not length_data: |
| 96 | + continue # Handle disconnection or data not available |
| 97 | + |
| 98 | + # Step 2: Unpack the length (4 bytes) |
| 99 | + packet_length = struct.unpack('!I', length_data)[0] |
| 100 | + |
| 101 | + # Step 3: Receive the full packet based on the length |
| 102 | + serialized_packet = receive_full_chunk(recv_socket, packet_length) |
| 103 | + if serialized_packet: |
| 104 | + # Step 4: Deserialize the packet using pickle |
| 105 | + packet = pickle.loads(serialized_packet) |
| 106 | + # Step 5: Extract the packet contents (text, visemes, audio) |
| 107 | + if 'text' in packet: |
| 108 | + print(f"Transcribed Text: {packet['text']}") |
| 109 | + if 'visemes' in packet: |
| 110 | + print(f"Visemes: {packet['visemes']}") |
| 111 | + # We're no longer playing audio, but you could process it if needed |
| 112 | + if 'audio' in packet: |
| 113 | + recv_queue.put(packet['audio']) |
| 114 | + |
| 115 | + try: |
| 116 | + send_thread = threading.Thread(target=send, args=(stop_event, send_queue)) |
| 117 | + send_thread.start() |
| 118 | + recv_thread = threading.Thread(target=recv, args=(stop_event, recv_queue)) |
| 119 | + recv_thread.start() |
| 120 | + |
| 121 | + input("Press Enter to stop...") |
| 122 | + |
| 123 | + except KeyboardInterrupt: |
| 124 | + print("Finished streaming.") |
| 125 | + |
| 126 | + finally: |
| 127 | + stop_event.set() |
| 128 | + recv_thread.join() |
| 129 | + send_thread.join() |
| 130 | + send_socket.close() |
| 131 | + recv_socket.close() |
| 132 | + print("Connection closed.") |
| 133 | + |
| 134 | + |
| 135 | +if __name__ == "__main__": |
| 136 | + parser = HfArgumentParser((ListenAndPlayArguments,)) |
| 137 | + (listen_and_play_kwargs,) = parser.parse_args_into_dataclasses() |
| 138 | + listen_and_dont_play(**vars(listen_and_play_kwargs)) |
0 commit comments