AD SPACE AVAILABLE · BRAND PARTNERS WELCOME

Setting Up Real-Time Voice Streaming with PlayHT in Conversational AI

Lianne Tan · 365Finds Editorial
Indexed 88,650 Wiki articles

Put 365 Wiki to work with your AI

Copy the prompt below, paste it into the AI you already use, then ask your question.

Download full Skill

Try it with the prompt first. If you use 365 Wiki often, install the full 365Wiki Skill so you do not have to paste it again. No regular AI? Gemini or Microsoft Copilot on the web will work.

365Wiki Skill

To build a conversational voice agent with PlayHT, you cannot rely on standard HTTP REST endpoints. Generating a complete audio file before playback introduces multi-second delays that immediately destroy conversational realism. Real-time dialogue requires bidirectional streaming over WebSockets, taking text tokens as they emerge from a large language model (LLM) and receiving raw audio chunks within 200 to 350 milliseconds.

At 365Finds, we evaluate voice engines based on three unforgiving metrics: time to first audio (TTFA), prosodic naturalness during multi-turn exchanges, and pipeline integration friction. PlayHT provides competitive building blocks for low-latency dialogue, but getting smooth, interruptible streaming requires understanding its two-step authentication handshake, model trade-offs, and audio buffer management.

+-------------------------------------------------------------+
| Conversational Voice Pipeline                               |
|                                                             |
|  [ User Voice ]                                             |
|        |                                                    |
|        v                                                    |
|  [ ASR Engine ] ----> [ LLM Stream ]                        |
|                             | (Punctuation Buffer)          |
|                             v                               |
|                    [ PlayHT WebSocket ]                     |
|                      - Play3.0-mini / PlayDialog            |
|                             | (Audio Chunks: PCM / Mulaw)   |
|                             v                               |
|                    [ WebRTC / Telephony Audio Player ]      |
|                             |                               |
|  [ User Barge-In ] -------> [ Flush Buffer & Abort Turn ]   |
+-------------------------------------------------------------+

1. The PlayHT WebSocket Architecture

Unlike traditional WebSocket APIs that let you connect directly to a persistent, static URI with basic query parameters, PlayHT enforces an explicit two-step connection flow:

  1. Authentication Handshake (HTTP POST): Your server calls https://api.play.ht/api/v4/websocket-auth with your API credentials.
  2. Endpoint Discovery: The API returns ephemeral, model-specific WebSocket URLs under websocket_urls.
  3. Socket Connection: Your application establishes a secure WebSocket connection (wss://) to the designated model URL.
  4. Frame Exchange: You push JSON commands containing text and voice parameters, receiving a start signal, sequential binary audio chunks, and an end marker.

This handshake adds a minor initial delay during cold-start connection setup. At 365Finds, we strongly recommend establishing and pooling warm WebSocket connections in your application backend rather than authenticating on every incoming user voice turn.


2. Authentication and Connection Setup

To initiate the session via standard HTTP/WebSocket tooling, send an authorization request:

POST /api/v4/websocket-auth HTTP/1.1
Host: api.play.ht
Authorization: Bearer YOUR_API_KEY
X-User-Id: YOUR_USER_ID
Content-Type: application/json

The response provides authenticated WebSocket URLs for supported real-time models:

{
  "websocket_urls": {
    "Play3.0-mini": "wss://...",
    "PlayDialog": "wss://..."
  }
}

Once connected to the returned URL, your server sends synthesis requests using a JSON payload:

{
  "text": "Hello! I can help you update your account settings right away.",
  "voice": "s3://voice-cloning-zero-shot/d9ff78ba-d016-47f6-b0ef-dd630f59414e/female-cs/manifest.json",
  "output_format": "raw",
  "sample_rate": 24000,
  "speed": 1.0
}

The server returns data across the socket in three phases:


3. Streaming Implementation with the Official Python SDK (pyht)

If you are developing in Python, PlayHT maintains the pyht library, which abstracts the handshake and socket protocol.

Install the package:

pip install pyht

Here is a minimal, production-ready streaming client:

import os
from pyht import Client
from pyht.client import TTSOptions
from pyht.types import Format

# Initialize client using credentials
client = Client(
    user_id=os.getenv("PLAY_HT_USER_ID"),
    api_key=os.getenv("PLAY_HT_API_KEY"),
)

# Configure voice options for low latency
options = TTSOptions(
    voice="s3://voice-cloning-zero-shot/d9ff78ba-d016-47f6-b0ef-dd630f59414e/female-cs/manifest.json",
    format=Format.FORMAT_RAW,
    sample_rate=24000,
    speed=1.0,
)

def stream_text_to_audio(text_prompt: str):
    """
    Streams audio chunks directly to an audio output consumer.
    """
    audio_stream = client.tts(text_prompt, options)
    for chunk in audio_stream:
        # Pass raw binary audio bytes to your output buffer, WebRTC track, or player
        yield chunk

4. Key Architectural Trade-offs: Play3.0-mini vs. PlayDialog

Choosing the right model is where conversational projects either succeed or suffer from awkward conversational stalls. PlayHT primarily offers two real-time engines:

Feature / MetricPlay3.0-miniPlayDialog
Time to First Audio (TTFA)~190 ms~350 ms
Streaming LatencyUnder 200 ms~300 to 400 ms
Conversational ContextSingle-prompt prosody; fast syntax processingAdaptive Speech Contextualizer (ASC); dynamic prosody
Primary StrengthRaw turn-taking speed and multilingual densityRealistic emotional shifts and natural turn pauses
365Finds Recommended UseStrict low-latency telephony, transactional customer serviceCharacter roleplay, high-empathy sales, narrative assistants

In conversational AI, human speech turn-taking thresholds hover around 600 to 800 milliseconds total pipeline latency. When speech-to-text (ASR) takes 250 milliseconds and LLM time-to-first-token takes 300 milliseconds, you only have 200 milliseconds left for text-to-speech. Under these strict timing budgets, Play3.0-mini is the pragmatic choice. PlayDialog sounds richer, but its ~350 ms TTFA will push total round-trip latency past 900 ms unless your upstream models are exceptionally fast.


5. Critical Engineering Practices for Conversational Voice

Setting up the socket is straightforward; mastering conversational flow is where production agents are made or broken.

Audio Format Selection

Text Chunking and Sentence Boundary Buffering

A common mistake is feeding individual LLM tokens directly to PlayHT. Sending words one by one damages acoustic context, resulting in disjointed cadence and bizarre inflection.

Instead, implement a lightweight punctuation buffer:

  1. Accumulate incoming LLM tokens until reaching sentence-ending or clause-ending punctuation (such as ., ,, ?, !, or a newline).
  2. For the first phrase of an agent's turn, flush aggressively on the first comma or short clause (3 to 6 words) to get immediate audio playback.
  3. For subsequent phrases, buffer complete sentences to allow PlayHT's voice engine to apply proper prosody.

Handling User Interruption (Barge-In)

When a user begins speaking while the bot is outputting speech, you must interrupt playback instantly:

  1. Your client-side audio player must immediately purge its local audio buffer.
  2. Discard any pending chunks received from the active PlayHT stream.
  3. Reset or terminate the synthesis task on your orchestrator server.

6. 365Finds' Evaluation

PlayHT delivers genuine low-latency streaming performance that comfortably powers production-grade conversational bots. The sub-200ms latency on Play3.0-mini is accurate to advertised numbers and allows developers to maintain sub-second total conversational turns.

What frustrates us is the friction in connection management: requiring an initial HTTP authentication call to retrieve dynamic WebSocket URLs introduces extra state tracking into backend orchestration. Furthermore, voice quality on Play3.0-mini occasionally suffers from flat inflection compared to PlayDialog. If emotional authenticity is your primary requirement and your infrastructure can tolerate 350ms TTFA, PlayDialog remains the more convincing voice model. For latency-first telephony agents, stick with Play3.0-mini paired with 8kHz Mu-law output.

References