Sruthú Fuaime Déthreoch
Ar an leathanach seo
Nuashonraithe an 2 Samhain, 2026 — Múnlaí fuaime. Tá roinnt múnlaí sa chúrsa seo curtha as feidhm: stopfaidh
tts-1,tts-1-hd, agusgpt-4o-mini-ttsag obair ar an 6 Eanáir, 2027 (is égpt-realtime-2.1-minian t-ionadaí atá luaite, ach deir treoir TTS OpenAI nach dtacaítear leis le/v1/audio/speech: aistrítear sintéis cainte chuig an Realtime API); stopfaidhgpt-realtime,gpt-4o-realtime, agus múnlaí fuaime oidhreachta ag obair ar an 20 Eanáir, 2027 (gpt-realtime-2.1,gpt-realtime-2.1-mini,gpt-audio-1.5); stopfaidhwhisper-1,gpt-4o-transcribe, agus/v1/audio/translationsag obair ar an 26 Feabhra, 2027 (gpt-transcribe,gpt-live-transcribe,v1/realtime/translations). Maidir le guth lán-dúbailte, tá GPT-Live 1 ar fáil san API ón 10 Meán Fómhair, 2026.
Sruthú Fuaime Déthreoch
Is é sruthú fuaime déthreoch croílár an Realtime API. Seolann tú píosaí fuaime ón micreafón go leanúnach, agus filleann an múnla píosaí fuaime freagartha go leanúnach. Tá an dá shruth neamhspleách agus is féidir leo oibriú ag an am céanna—sin an fáth a mbíonn an comhrá chomh nádúrtha sin.
Formáid Fuaime PCM16
Úsáideann an Realtime API formáid 24 kHz monó 16-giotán PCM. Is formáid amh, neamh-chomhbhrúite í seo: is slánuimhir shínithe 16-giotán gach sampla. Tugann an rogha seo tosaíocht do mhoill íseal seachas éifeachtúlacht bandaleithead.
Seoltar píosaí fuaime ionchódaithe i Base64 laistigh d’imeachtaí JSON. De ghnáth, léiríonn gach píosa 20 go 100 ms d’fhuaime.
Fuaime a Sheoladh: Gabháil ón Micreafón
Seo conas an micreafón a ghabháil agus an fhuaim a shruthú:
import asyncio
import sounddevice as sd
import numpy as np
import base64
import json
SAMPLE_RATE = 24000
CHUNK_DURATION_MS = 100
CHUNK_SIZE = int(SAMPLE_RATE * CHUNK_DURATION_MS / 1000)
async def stream_microphone(ws):
"""Capture the microphone and send chunks to the Realtime API."""
loop = asyncio.get_event_loop()
audio_queue = asyncio.Queue()
def audio_callback(indata, frames, time_info, status):
if status:
print(f"Audio warning: {status}")
# Convert to int16 and enqueue
pcm_data = (indata[:, 0] * 32767).astype(np.int16)
loop.call_soon_threadsafe(audio_queue.put_nowait, pcm_data)
# Start capture
stream = sd.InputStream(
samplerate=SAMPLE_RATE,
channels=1,
dtype="float32",
blocksize=CHUNK_SIZE,
callback=audio_callback
)
with stream:
print("Microphone active — speak now...")
while True:
pcm_data = await audio_queue.get()
audio_b64 = base64.b64encode(pcm_data.tobytes()).decode("utf-8")
await ws.send(json.dumps({
"type": "input_audio_buffer.append",
"audio": audio_b64
}))
An Maolán Fuaime ar an bhFreastalaí
Cruinníonn na píosaí a sheoltar trí input_audio_buffer.append i maolán ar an bhfreastalaí. Déantar próiseáil ar an maolán seo ar dhá bhealach:
- Mód VAD uathoibríoch (
server_vad): Brathann an freastalaí cathain a stopann tú ag caint agus tiomnaíonn sé an maolán go huathoibríoch. - Mód láimhe: Seolann tú
input_audio_buffer.commitgo sainráite chun próiseáil a thosú.
# Manually commit the audio buffer
await ws.send(json.dumps({
"type": "input_audio_buffer.commit"
}))
# Or clear the buffer without processing it
await ws.send(json.dumps({
"type": "input_audio_buffer.clear"
}))
Fuaim Freagartha a Fháil
Tagann freagraí fuaime i bpíosaí trí imeachtaí response.output_audio.delta. Caithfidh tú iad a dhíchódú agus a sheinm go leanúnach:
import pyaudio
async def play_response_audio(ws):
"""Receive and play response audio."""
pa = pyaudio.PyAudio()
player = pa.open(
format=pyaudio.paInt16,
channels=1,
rate=SAMPLE_RATE,
output=True,
frames_per_buffer=CHUNK_SIZE
)
try:
async for raw_message in ws:
event = json.loads(raw_message)
if event["type"] == "response.output_audio.delta":
# Decode the Base64 audio chunk
audio_bytes = base64.b64decode(event["delta"])
player.write(audio_bytes)
elif event["type"] == "response.output_audio.done":
print("Audio response finished")
elif event["type"] == "response.output_audio_transcript.delta":
# Text transcription of the response
print(event["delta"], end="", flush=True)
finally:
player.stop_stream()
player.close()
pa.terminate()
Feidhmchlár Iomlán: Comhrá Gutha
Seo conas gabháil agus athsheinm a chur le chéile le haghaidh comhrá iomláin:
async def conversation_vocale():
headers = {
"Authorization": f"Bearer {OPENAI_API_KEY}"
}
async with websockets.connect(URL, additional_headers=headers) as ws:
# Wait for session.created
await ws.recv()
# Configure the session
await ws.send(json.dumps({
"type": "session.update",
"session": {
"type": "realtime",
"output_modalities": ["audio"],
"instructions": "You are a voice assistant. Respond in English.",
"audio": {
"input": {
"format": {"type": "audio/pcm", "rate": 24000},
"turn_detection": {
"type": "server_vad",
"threshold": 0.5,
"silence_duration_ms": 700
}
},
"output": {
"format": {"type": "audio/pcm", "rate": 24000},
"voice": "marin"
}
}
}
}))
await ws.recv() # session.updated
# Launch capture and playback in parallel
await asyncio.gather(
stream_microphone(ws),
play_response_audio(ws)
)
asyncio.run(conversation_vocale())
Sruthanna Comhthreomhara a Bhainistiú
Is é an dúshlán a bhaineann le sruthú déthreoch ná go bhfuil tú ag seoladh agus ag fáil ag an am céanna ar an WebSocket céanna. Seolann asyncio.gather an dá chorúitin i gcomhthreomhar, ach roinneann siad an oibiacht WebSocket céanna. Láimhseálann an leabharlann websockets an comhthreomhaireacht seo i gceart.
Príomhphointí
- Tarchuirtear fuaim mar PCM 16-giotán monó 24 kHz, ionchódaithe i Base64 in imeachtaí JSON
- De ghnáth, is píosaí fuaime 20 go 100 ms iad na píosaí chun comhréir mhaith a bhaint amach idir moill agus forchostas
- Cruinníonn an maolán fuaime ar an bhfreastalaí píosaí go dtí go ndéantar tiomnú (uathoibríoch i mód VAD)
- Tarlaíonn athsheinm na freagartha píosa ar phíosa trí
response.output_audio.delta - Cuireann
asyncio.gatherar chumas gabháil agus athsheinm a dhéanamh ag an am céanna ar an WebSocket céanna