Léim go dtí an príomhábhar
Gaeilge— Roghnaigh teanga
Roghchlár

Sruthú fuaime i bhfíor-am

Ceacht 12 as 18 Nuashonraithe 3 Samhain 2026 Forbróir
Ar an leathanach seo
  1. Sruthú fuaime i bhfíor-am
  2. Sruthú leis an TTS API
  3. Latency a thomhas
  4. Sruthú neamhshioncrónach
  5. Maolán réamhlíonta
  6. Comhtháthú le píblíne LLM + TTS
  7. Príomhphointí

Nuashonrú 2 Samhain, 2026 — Múnlaí fuaime. Tá roinnt múnlaí sa chúrsa seo imithe in éag: stopfaidh tts-1, tts-1-hd, agus gpt-4o-mini-tts ag obair ar 6 Eanáir, 2027 (an t-ionadaí: gpt-realtime-2.1-mini, a deir treoir TTS OpenAI nach dtacaítear leis trí /v1/audio/speech: aistrítear sintéis gutha chuig an Realtime API); gpt-realtime, gpt-4o-realtime, agus múnlaí fuaime oidhreachta ar 20 Eanáir, 2027 (gpt-realtime-2.1, gpt-realtime-2.1-mini, gpt-audio-1.5); whisper-1, gpt-4o-transcribe, agus /v1/audio/translations ar 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. Nuashonraithe 3 Samhain, 2026: Phróiseáil an píblíne LLM → TTS roimhe seo aon imeacht a raibh réimse delta ann, lena n-áirítear argóintí glaonna feidhme nó achoimrí réasúnaíochta; anois scagtar go docht le haghaidh response.output_text.delta, an téacs freagartha iarbhír.

Sruthú fuaime i bhfíor-am

I ngníomhaire gutha, cuireann fanacht leis an gcomhad fuaime iomlán a ghiniúint sula dtosaíonn tú an seinm moill nach bhfuil inghlactha. Ligeann sruthú TTS duit tosú ag seinm chomh luath agus a thagann na chéad bhearta, ag gearradh an ama go dtí an chéad fhreagra síos go dtí cúpla céad milleasoicind.

Sruthú leis an TTS API

Tacaíonn an TTS API le sruthú go dúchasach. In ionad fanacht leis an gcomhad iomlán, faigheann tú an fhuaim i smutání:

from openai import OpenAI
import pyaudio

client = OpenAI()

def stream_tts_to_speaker(text: str, voice: str = "alloy"):
    """Gin agus seinm fuaime i mód sruthaithe."""
    # Tosaigh an seinnteoir fuaime
    pa = pyaudio.PyAudio()
    player = pa.open(
        format=pyaudio.paInt16,
        channels=1,
        rate=24000,
        output=True
    )

    try:
        # Cruthaigh an fhreagairt sruthaithe
        with client.audio.speech.with_streaming_response.create(
            model="tts-1",
            voice=voice,
            input=text,
            response_format="pcm"  # PCM amh le haghaidh seinm dhíreach
        ) as response:
            # Léigh agus seinm smután ar smután
            for chunk in response.iter_bytes(chunk_size=4096):
                player.write(chunk)

    finally:
        player.stop_stream()
        player.close()
        pa.terminate()

stream_tts_to_speaker("Hello, here is a real-time streaming response.")

Is idéalach an formáid pcm le haghaidh sruthú toisc nach gá aon díchódú: tá na bhearta amha réidh le seinm láithreach.

Latency a thomhas

Is é an tAm go dtí an Chéad Bheart (TTFB) an príomhthomhas do fheidhmíocht sruthaithe:

import time

def measure_tts_latency(text: str, voice: str = "alloy") -> dict:
    """Tomhas latencies sruthaithe TTS."""
    start_time = time.time()
    first_byte_time = None
    total_bytes = 0

    with client.audio.speech.with_streaming_response.create(
        model="tts-1",
        voice=voice,
        input=text,
        response_format="pcm"
    ) as response:
        for chunk in response.iter_bytes(chunk_size=4096):
            if first_byte_time is None:
                first_byte_time = time.time()
            total_bytes += len(chunk)

    end_time = time.time()

    return {
        "ttfb_ms": round((first_byte_time - start_time) * 1000),
        "total_ms": round((end_time - start_time) * 1000),
        "total_bytes": total_bytes,
        "audio_duration_s": round(total_bytes / (24000 * 2), 2)
    }

metrics = measure_tts_latency("Hello, how are you?")
print(f"TTFB: {metrics['ttfb_ms']}ms, Total: {metrics['total_ms']}ms")

Sruthú neamhshioncrónach

Le haghaidh feidhmchláir taobh freastalaí, úsáid an cliant neamhshioncrónach:

from openai import AsyncOpenAI
import asyncio

async_client = AsyncOpenAI()

async def stream_tts_async(text: str, voice: str = "alloy"):
    """Sruthú TTS neamhshioncrónach do fhreastalaithe."""
    chunks = []

    async with async_client.audio.speech.with_streaming_response.create(
        model="tts-1",
        voice=voice,
        input=text,
        response_format="pcm"
    ) as response:
        async for chunk in response.iter_bytes(chunk_size=4096):
            chunks.append(chunk)
            # Anseo, sheolfá an smután chuig an gcliant trí WebSocket
            yield chunk

# Úsáid i bhfreastalaí FastAPI
from fastapi import FastAPI
from fastapi.responses import StreamingResponse

app = FastAPI()

@app.get("/tts/stream")
async def tts_stream(text: str, voice: str = "alloy"):
    return StreamingResponse(
        stream_tts_async(text, voice),
        media_type="audio/pcm"
    )

Maolán réamhlíonta

Chun seinm réidh a chinntiú gan bearnaí, carn maolán beag sula dtosaíonn tú:

async def buffered_tts_playback(
    text: str,
    voice: str = "alloy",
    buffer_size: int = 3  # Líon na smutání le réamh-lódáil
):
    """Seinm TTS le maolán réamhlíonta."""
    pa = pyaudio.PyAudio()
    player = pa.open(
        format=pyaudio.paInt16,
        channels=1,
        rate=24000,
        output=True
    )

    buffer = []
    playback_started = False

    try:
        async with async_client.audio.speech.with_streaming_response.create(
            model="tts-1",
            voice=voice,
            input=text,
            response_format="pcm"
        ) as response:
            async for chunk in response.iter_bytes(chunk_size=4096):
                buffer.append(chunk)

                if not playback_started and len(buffer) >= buffer_size:
                    playback_started = True
                    # Scuir an maolán tosaigh
                    for buffered_chunk in buffer:
                        player.write(buffered_chunk)
                    buffer.clear()
                elif playback_started:
                    player.write(chunk)

        # Seinm na smutání atá fágtha
        for remaining in buffer:
            player.write(remaining)

    finally:
        player.stop_stream()
        player.close()
        pa.terminate()

Comhtháthú le píblíne LLM + TTS

I ngníomhaire gutha nach bhfuil bunaithe ar Realtime, is féidir leat sruthú LLM a chomhcheangal le sruthú TTS:

async def llm_to_tts_pipeline(user_message: str):
    """Píblíne: LLM Sruthaithe → TTS Sruthaithe i bhfíor-am."""
    # Céim 1: Carn freagairt LLM de réir abairte
    sentence_buffer = ""

    stream = client.responses.create(
        model="gpt-5.6-luna",
        input=[{"role": "user", "content": user_message}],
        stream=True
    )

    for event in stream:
        # Níor chóir ach téacs freagartha a labhairt
        if event.type == "response.output_text.delta":
            sentence_buffer += event.delta

            # Brath deireadh na habairte
            if sentence_buffer.rstrip().endswith((".", "!", "?")):
                sentence = sentence_buffer.strip()
                sentence_buffer = ""

                # Céim 2: Sruthaigh an abairt seo chuig TTS
                stream_tts_to_speaker(sentence)

    # Próiseáil an maolán atá fágtha
    if sentence_buffer.strip():
        stream_tts_to_speaker(sentence_buffer.strip())

Príomhphointí

  • Gearrann sruthú TTS an TTFB síos go dtí cúpla céad milleasoicind trí thosú ag seinm sula gcríochnaíonn an ghiniúint
  • Is é an formáid pcm an ceann is fearr le haghaidh sruthú: gan aon díchódú ag teastáil, seinm dhíreach
  • Coscann maolán réamhlíonta de 2–3 smután bearnaí ag tús na seinme
  • Tá an cliant neamhshioncrónach riachtanach do fhreastalaithe a láimhseálann ilcheangail chomhuaineacha
  • Cuireann comhcheangal LLM sruthaithe agus TTS sruthaithe ar chumas gníomhaire gutha freagrach gan an Realtime API