Implementation:Openai Openai python Local Audio Player
Appearance
| Knowledge Sources | |
|---|---|
| Domains | Audio, Client_Helpers |
| Last Updated | 2026-02-15 00:00 GMT |
Overview
Concrete helper class for playing audio through the local sound device provided by the OpenAI Python SDK.
Description
The LocalAudioPlayer class provides play() for complete audio playback and play_stream() for streaming audio playback. It accepts TTS responses (HttpxBinaryResponseContent), numpy arrays, and async audio generators. It uses the sounddevice library for audio output.
Usage
Instantiate with an optional should_stop callback. Call play() with a TTS response or numpy array, or play_stream() with an async generator of audio chunks.
Code Reference
Source Location
- Repository: openai-python
- File: src/openai/helpers/local_audio_player.py
- Lines: L19-165
Signature
class LocalAudioPlayer:
def __init__(
self,
should_stop: Callable[[], bool] | None = None,
) -> None:
"""
Args:
should_stop: Optional callback returning True to stop playback.
"""
async def play(
self,
input: Union[
npt.NDArray[np.int16],
npt.NDArray[np.float32],
HttpxBinaryResponseContent,
AsyncStreamedBinaryAPIResponse,
StreamedBinaryAPIResponse,
],
) -> None:
"""Plays audio from various input types."""
async def play_stream(
self,
buffer_stream: AsyncGenerator[Union[npt.NDArray[Any], None], None],
) -> None:
"""Plays audio from a streaming generator."""
Import
from openai.helpers import LocalAudioPlayer
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| input | NDArray or HttpxBinaryResponseContent | Yes (play) | Audio data to play |
| buffer_stream | AsyncGenerator | Yes (play_stream) | Async generator of audio chunks |
| should_stop | Callable[[], bool] | No | Stop predicate for interruption |
Outputs
| Name | Type | Description |
|---|---|---|
| (audio playback) | None | Audio played through local sound device |
Usage Examples
Play TTS Response
import asyncio
from openai import OpenAI
from openai.helpers import LocalAudioPlayer
client = OpenAI()
response = client.audio.speech.create(
model="tts-1",
voice="alloy",
input="Hello from the OpenAI SDK!",
response_format="pcm",
)
player = LocalAudioPlayer()
asyncio.run(player.play(response))
Streaming Playback with Stop Control
import asyncio
stop_flag = False
def should_stop():
return stop_flag
player = LocalAudioPlayer(should_stop=should_stop)
with client.audio.speech.with_streaming_response.create(
model="tts-1",
voice="nova",
input="A long text to be read aloud.",
response_format="pcm",
) as response:
asyncio.run(player.play(response))
Related Pages
Implements Principle
Requires Environment
Page Connections
Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment