|
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
|
@@ -45,15 +47,76 @@ def __init__(self) -> None:
|
45 | 47 | self.audio_stream: sd.InputStream | None = None
|
46 | 48 | self.audio_player: sd.OutputStream | None = None
|
47 | 49 | self.recording = False
|
| 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[self.chunk_position:self.chunk_position + samples_to_copy] |
| 99 | + # More efficient: direct assignment for mono audio instead of reshape |
| 100 | + outdata[samples_filled:samples_filled + samples_to_copy, 0] = chunk_data |
| 101 | + samples_filled += samples_to_copy |
| 102 | + self.chunk_position += samples_to_copy |
| 103 | + |
| 104 | + # If we've used up the entire chunk, reset for next iteration |
| 105 | + if self.chunk_position >= len(self.current_audio_chunk): |
| 106 | + self.current_audio_chunk = None |
| 107 | + self.chunk_position = 0 |
48 | 108 |
|
49 | 109 | async def run(self) -> None:
|
50 | 110 | print("Connecting, may take a few seconds...")
|
51 | 111 |
|
52 |
| - # Initialize audio player |
| 112 | + # Initialize audio player with callback |
| 113 | + chunk_size = int(SAMPLE_RATE * CHUNK_LENGTH_S) |
53 | 114 | self.audio_player = sd.OutputStream(
|
54 | 115 | channels=CHANNELS,
|
55 | 116 | samplerate=SAMPLE_RATE,
|
56 | 117 | dtype=FORMAT,
|
| 118 | + callback=self._output_callback, |
| 119 | + blocksize=chunk_size, # Match our chunk timing for better alignment |
57 | 120 | )
|
58 | 121 | self.audio_player.start()
|
59 | 122 |
|
@@ -146,15 +209,24 @@ async def _on_event(self, event: RealtimeSessionEvent) -> None:
|
146 | 209 | elif event.type == "audio_end":
|
147 | 210 | print("Audio ended")
|
148 | 211 | elif event.type == "audio":
|
149 |
| - # Play audio through speakers |
| 212 | + # Enqueue audio for callback-based playback |
150 | 213 | 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}") |
| 214 | + try: |
| 215 | + self.output_queue.put_nowait(np_audio) |
| 216 | + except queue.Full: |
| 217 | + # Queue is full - only drop if we have significant backlog |
| 218 | + # This prevents aggressive dropping that could cause choppiness |
| 219 | + if self.output_queue.qsize() > 8: # Keep some buffer |
| 220 | + try: |
| 221 | + self.output_queue.get_nowait() |
| 222 | + self.output_queue.put_nowait(np_audio) |
| 223 | + except queue.Empty: |
| 224 | + pass |
| 225 | + # If queue isn't too full, just skip this chunk to avoid blocking |
156 | 226 | elif event.type == "audio_interrupted":
|
157 | 227 | print("Audio interrupted")
|
| 228 | + # Signal the output callback to clear its queue and state |
| 229 | + self.interrupt_event.set() |
158 | 230 | elif event.type == "error":
|
159 | 231 | print(f"Error: {event.error}")
|
160 | 232 | elif event.type == "history_updated":
|
|
0 commit comments