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