|
1 | 1 | import asyncio |
| 2 | +import queue |
2 | 3 | import sys |
| 4 | +import threading |
3 | 5 |
|
4 | 6 | import numpy as np |
5 | 7 | import sounddevice as sd |
@@ -46,14 +48,77 @@ def __init__(self) -> None: |
46 | 48 | self.audio_player: sd.OutputStream | None = None |
47 | 49 | self.recording = False |
48 | 50 |
|
| 51 | + # Audio output state for callback system |
| 52 | + self.output_queue: queue.Queue[np.ndarray] = queue.Queue(maxsize=10) # Buffer more chunks |
| 53 | + self.interrupt_event = threading.Event() |
| 54 | + self.current_audio_chunk: np.ndarray | None = None |
| 55 | + self.chunk_position = 0 |
| 56 | + |
| 57 | + def _output_callback(self, outdata: np.ndarray, frames: int, time, status) -> None: |
| 58 | + """Callback for audio output - handles continuous audio stream from server.""" |
| 59 | + if status: |
| 60 | + print(f"Output callback status: {status}") |
| 61 | + |
| 62 | + # Check if we should clear the queue due to interrupt |
| 63 | + if self.interrupt_event.is_set(): |
| 64 | + # Clear the queue and current chunk state |
| 65 | + while not self.output_queue.empty(): |
| 66 | + try: |
| 67 | + self.output_queue.get_nowait() |
| 68 | + except queue.Empty: |
| 69 | + break |
| 70 | + self.current_audio_chunk = None |
| 71 | + self.chunk_position = 0 |
| 72 | + self.interrupt_event.clear() |
| 73 | + outdata.fill(0) |
| 74 | + return |
| 75 | + |
| 76 | + # Fill output buffer from queue and current chunk |
| 77 | + outdata.fill(0) # Start with silence |
| 78 | + samples_filled = 0 |
| 79 | + |
| 80 | + while samples_filled < len(outdata): |
| 81 | + # If we don't have a current chunk, try to get one from queue |
| 82 | + if self.current_audio_chunk is None: |
| 83 | + try: |
| 84 | + self.current_audio_chunk = self.output_queue.get_nowait() |
| 85 | + self.chunk_position = 0 |
| 86 | + except queue.Empty: |
| 87 | + # No more audio data available - this causes choppiness |
| 88 | + # Uncomment next line to debug underruns: |
| 89 | + # print(f"Audio underrun: {samples_filled}/{len(outdata)} samples filled") |
| 90 | + break |
| 91 | + |
| 92 | + # Copy data from current chunk to output buffer |
| 93 | + remaining_output = len(outdata) - samples_filled |
| 94 | + remaining_chunk = len(self.current_audio_chunk) - self.chunk_position |
| 95 | + samples_to_copy = min(remaining_output, remaining_chunk) |
| 96 | + |
| 97 | + if samples_to_copy > 0: |
| 98 | + chunk_data = self.current_audio_chunk[ |
| 99 | + self.chunk_position : self.chunk_position + samples_to_copy |
| 100 | + ] |
| 101 | + # More efficient: direct assignment for mono audio instead of reshape |
| 102 | + outdata[samples_filled : samples_filled + samples_to_copy, 0] = chunk_data |
| 103 | + samples_filled += samples_to_copy |
| 104 | + self.chunk_position += samples_to_copy |
| 105 | + |
| 106 | + # If we've used up the entire chunk, reset for next iteration |
| 107 | + if self.chunk_position >= len(self.current_audio_chunk): |
| 108 | + self.current_audio_chunk = None |
| 109 | + self.chunk_position = 0 |
| 110 | + |
49 | 111 | async def run(self) -> None: |
50 | 112 | print("Connecting, may take a few seconds...") |
51 | 113 |
|
52 | | - # Initialize audio player |
| 114 | + # Initialize audio player with callback |
| 115 | + chunk_size = int(SAMPLE_RATE * CHUNK_LENGTH_S) |
53 | 116 | self.audio_player = sd.OutputStream( |
54 | 117 | channels=CHANNELS, |
55 | 118 | samplerate=SAMPLE_RATE, |
56 | 119 | dtype=FORMAT, |
| 120 | + callback=self._output_callback, |
| 121 | + blocksize=chunk_size, # Match our chunk timing for better alignment |
57 | 122 | ) |
58 | 123 | self.audio_player.start() |
59 | 124 |
|
@@ -146,15 +211,24 @@ async def _on_event(self, event: RealtimeSessionEvent) -> None: |
146 | 211 | elif event.type == "audio_end": |
147 | 212 | print("Audio ended") |
148 | 213 | elif event.type == "audio": |
149 | | - # Play audio through speakers |
| 214 | + # Enqueue audio for callback-based playback |
150 | 215 | np_audio = np.frombuffer(event.audio.data, dtype=np.int16) |
151 | | - if self.audio_player: |
152 | | - try: |
153 | | - self.audio_player.write(np_audio) |
154 | | - except Exception as e: |
155 | | - print(f"Audio playback error: {e}") |
| 216 | + try: |
| 217 | + self.output_queue.put_nowait(np_audio) |
| 218 | + except queue.Full: |
| 219 | + # Queue is full - only drop if we have significant backlog |
| 220 | + # This prevents aggressive dropping that could cause choppiness |
| 221 | + if self.output_queue.qsize() > 8: # Keep some buffer |
| 222 | + try: |
| 223 | + self.output_queue.get_nowait() |
| 224 | + self.output_queue.put_nowait(np_audio) |
| 225 | + except queue.Empty: |
| 226 | + pass |
| 227 | + # If queue isn't too full, just skip this chunk to avoid blocking |
156 | 228 | elif event.type == "audio_interrupted": |
157 | 229 | print("Audio interrupted") |
| 230 | + # Signal the output callback to clear its queue and state |
| 231 | + self.interrupt_event.set() |
158 | 232 | elif event.type == "error": |
159 | 233 | print(f"Error: {event.error}") |
160 | 234 | elif event.type == "history_updated": |
|
0 commit comments