i am using open ai real time model can i get audio...
# ask-ai
r
i am using open ai real time model can i get audio chunk (i mean user's audio) before send to open ai ?
t
Thanks for reaching out, Av. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Absolutely! LiveKit is designed to provide audio chunks of a user's audio in real-time, even before sending them to OpenAI or other services. It processes and streams user audio in small chunks, usually 50ms frames, using a handy
AudioByteStream
utility. These chunks can then be forwarded to AI services like OpenAI through WebSocket connections as they’re captured, which helps enable smooth, low-latency streaming interactions. To give you a clearer picture of how this works with OpenAI integration: • The audio is resampled to a 24kHz mono format and chunked using
AudioByteStream
. • Each chunk is encoded in base64 and sent right away using the
input_audio_buffer.append
event over a WebSocket connection to OpenAI's Realtime API. • OpenAI needs at least 100ms of accumulated audio before it processes a full segment, but don’t worry—the chunks themselves are sent as soon as they’re ready. This setup is actually quite popular for real-time voice applications, like ChatGPT's Advanced Voice mode. In these cases, user audio is streamed from the client to the backend using WebRTC via LiveKit, and then forwarded in chunks to OpenAI for transcription and response generation. I hope this helps clarify how everything works together! Sources: livekit-plugins/livekit-plugins-openai/livekit/plugins/openai/realtime/real... | AI Agents Framework | livekit/livekit_composite | DeepWiki | OpenAI and LiveKit partner to turn Advanced Voice into an API | OpenAI and LiveKit partner to turn Advanced Voice into an API | OpenAI and LiveKit partner to turn Advanced Voice into an API
r
give me a code
t
I'd love to share a helpful Python example for streaming audio chunks from LiveKit to OpenAI in real-time with you:
Copy code
async def send_task(ws: aiohttp.ClientWebSocketResponse) -> None:
    # Forward audio to OpenAI in chunks of 50ms
    audio_bstream = utils.audio.AudioByteStream(
        sample_rate=24000,  # 24kHz
        num_channels=1,  # Mono
        samples_per_channel=24000 // 20,  # 50ms chunks
    )

    async for data in self._input_ch:
        frames = []
        if isinstance(data, rtc.AudioFrame):
            frames.extend(audio_bstream.write(data.data.tobytes()))
        elif isinstance(data, self._FlushSentinel):
            frames.extend(audio_bstream.flush())

        for frame in frames:
            encoded_frame = {
                "type": "input_audio_buffer.append",
                "audio": base64.b64encode(frame.data.tobytes()).decode("utf-8"),
            }
            await ws.send_json(encoded_frame)
And here’s a JavaScript/TypeScript example that might be just what you need:
Copy code
import { AudioByteStream } from '@livekit/agents';
import { WebSocket } from 'ws';

class OpenAIRealtimeSession {
  private audioStream: AudioByteStream;
  private ws: WebSocket;

  constructor() {
    this.audioStream = new AudioByteStream(24000, 1, 24000 / 20); // 50ms chunks
  }

  async sendAudioChunk(audioFrame) {
    const frames = this.audioStream.write(new Int16Array(audioFrame.data).buffer);
    for (const frame of frames) {
      const base64Audio = Buffer.from(frame.data.buffer).toString('base64');
      const message = {
        type: 'input_audio_buffer.append',
        audio: base64Audio
      };
      this.ws.send(JSON.stringify(message));
    }
  }
}
These examples should help you process and send audio chunks smoothly to OpenAI's Realtime API. If you have any questions or need more guidance, please don't hesitate to ask—I’m here to help! Sources: OpenAI and LiveKit partner to turn Advanced Voice into an API | livekit-plugins/livekit-plugins-resemble/README.md | agents/src/inference/stt.ts
r
i want to python code. and save each audio file
t
I don't have the answer you're looking for. You could also try asking your question: • in one of the other Slack channels or • to https://deepwiki.com/livekit/livekit_composite which is trained on all LiveKit source code If you find the answer, please post it here to help others!