fix(examples): make sure audio playback finishes (#340)

Previously the stream was closing as soon as all the audio was added but
didn't wait for it to be finished. Additionally the audio might seem
chopped off if there is no additional silence so this PR also adds one
second of silence before exiting the program.
This commit is contained in:
Rohan Mehta 2025-03-25 15:22:55 -04:00 committed by GitHub
commit a0c5abce8f
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 6 additions and 0 deletions

View file

@ -1,6 +1,8 @@
import asyncio import asyncio
import random import random
import numpy as np
from agents import Agent, function_tool from agents import Agent, function_tool
from agents.extensions.handoff_prompt import prompt_with_handoff_instructions from agents.extensions.handoff_prompt import prompt_with_handoff_instructions
from agents.voice import ( from agents.voice import (
@ -78,6 +80,9 @@ async def main():
elif event.type == "voice_stream_event_lifecycle": elif event.type == "voice_stream_event_lifecycle":
print(f"Received lifecycle event: {event.event}") print(f"Received lifecycle event: {event.event}")
# Add 1 second of silence to the end of the stream to avoid cutting off the last audio.
player.add_audio(np.zeros(24000 * 1, dtype=np.int16))
if __name__ == "__main__": if __name__ == "__main__":
asyncio.run(main()) asyncio.run(main())

View file

@ -62,6 +62,7 @@ class AudioPlayer:
return self return self
def __exit__(self, exc_type, exc_value, traceback): def __exit__(self, exc_type, exc_value, traceback):
self.stream.stop() # wait for the stream to finish
self.stream.close() self.stream.close()
def add_audio(self, audio_data: npt.NDArray[np.int16]): def add_audio(self, audio_data: npt.NDArray[np.int16]):