AD SPACE AVAILABLE · BRAND PARTNERS WELCOME

Integrating Voicemaker WebSocket API and ProPlus Turbo for Real-Time Voice Agents

Daly Zaloom · 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

In conversational voice agents, latency dictates natural interaction. When developers rely on traditional HTTP REST endpoints for Text-to-Speech (TTS), speech synthesis only begins after the entire sentence is rendered and returned over a closed HTTP request cycle. This induces turn-taking delays of 1,200 to 2,500 milliseconds—an awkward silence that shatters conversational realism.

At 365Finds, our benchmark recommendation for interactive agents is straightforward: pair Voicemaker's persistent WebSocket streaming interface with the ProPlus Turbo engine. This architecture bypasses HTTP handshake overhead, leverages Voicemaker's sub-300ms generation pipeline, and delivers base64-encoded audio chunks asynchronously to achieve human-paced, turn-by-turn dialogue.


Architecture: LLM to Streaming Audio Pipeline

A low-latency voice agent connects three decoupled streaming components:

[User Audio] ──► [STT Stream] ──► [Streaming LLM]
                                       │ (Token Stream)
                                       ▼
                              ┌──────────────────────┐
                              │ Sentence Buffer      │
                              │ (Clause / Punctuation)
                              └──────────────────────┘
                                       │ (Text Chunks)
                                       ▼
                         ┌─────────────────────────────┐
                         │ Voicemaker WebSocket Client │
                         │ (wss://.../voice/convert)   │
                         └─────────────────────────────┘
                                       │ (Base64 Audio Chunks)
                                       ▼
                       [Audio Player / WebRTC / Telephony]

To optimize Time-to-First-Audio (TTFA):

  1. Streaming LLM to Sentence Buffer: Never wait for complete paragraphs. Buffer incoming tokens until a linguistic boundary is reached (commas, periods, semicolons, question marks) with a minimum length threshold (e.g., 25–40 characters).
  2. Buffer to Voicemaker WebSocket: Send the sentence chunk as a structured JSON conversion payload over the open WebSocket.
  3. Chunk-by-Chunk Audio Playback: Ingest the base64-encoded audio chunks sequentially, decode them into raw bytes, and pipe them directly into a client-side playback buffer or telephony track without waiting for isFinal: true.

1. WebSocket Endpoint and Authentication

Voicemaker provides a dedicated real-time synthesis endpoint:

wss://developer.voicemaker.in/api/v1/voice/convert

Connection Handshake

Authentication takes place during the initial WebSocket handshake via the HTTP Authorization header. You cannot pass tokens inside the JSON body.


2. Request Payload Configuration

Once connected, conversion requests are transmitted as JSON strings. Each message triggers a single conversion task.

Essential Parameters for ProPlus Turbo

To achieve real-time latency, configure ProEngine as "turbo":

{
  "VoiceId": "ai3-Jony",
  "LanguageCode": "en-US",
  "Text": "Good morning! How can I assist with your booking today?",
  "ProEngine": "turbo",
  "Engine": "neural",
  "OutputFormat": "mp3",
  "SampleRate": "48000",
  "MasterSpeed": "0",
  "MasterVolume": "0",
  "MasterPitch": "0"
}

Key Parameter Reference

ParameterTypeRequiredValues / Notes
VoiceIdStringYesTarget voice ID (2–70 characters), e.g., ai3-Jony or specific ProPlus voices.
LanguageCodeStringYesRegional code (e.g., en-US, en-GB, or multi-lang for Pro voices).
TextStringYesText string to synthesize (maximum 3,000 characters). Supports SSML.
ProEngineStringNoSet to "turbo" for low latency (~250–300 ms). Default is "highres".
OutputFormatStringNo"mp3", "wav", "ogg", "aac", "opus", "ulaw", "alaw". Default: "mp3".
SampleRateStringNo"48000", "24000", "16000", "8000". "48000" recommended for web; "8000" for telephony.
StabilityNumberNo0 to 100 (Default 50). Controls vocal variance.
SimilarityNumberNo0 to 100 (Default 80). Controls voice clone fidelity.

365Finds Format Selection Recommendation:

  • For WebRTC, Web, or Mobile Apps, select OutputFormat: "mp3" at SampleRate: "48000". Voicemaker's documentation specifically notes that MP3 provides the lowest latency streaming path over WebSocket.
  • For Telephony / SIP / IVR (Twilio, FreeSWITCH), specify OutputFormat: "ulaw" or "alaw" at SampleRate: "8000". Delivering μ-law audio directly eliminates server-side resampling pipelines.

3. Streaming Response Lifecycle

The Voicemaker server returns responses asynchronously as JSON payloads:

Intermediate Audio Chunk

{
  "success": true,
  "audio": "SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU4Ljc2..."
}

Final Chunk

{
  "success": true,
  "audio": "SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU4Ljc2...",
  "isFinal": true
}

Response Mechanics


4. Complete Node.js Implementation

Below is a reference implementation showing how a voice agent server establishes a persistent WebSocket connection to Voicemaker, manages sentence boundary buffering, and streams base64 audio chunks directly to an output stream:

import WebSocket from 'ws';

class VoicemakerTTSStreamer {
  constructor(apiKey) {
    this.apiKey = apiKey;
    this.wsUrl = 'wss://developer.voicemaker.in/api/v1/voice/convert';
    this.ws = null;
    this.isConnected = false;
    this.responseCallbacks = [];
  }

  // 1. Establish persistent WebSocket connection
  connect() {
    return new Promise((resolve, reject) => {
      this.ws = new WebSocket(this.wsUrl, {
        headers: {
          Authorization: `Bearer ${this.apiKey}`,
        },
      });

      this.ws.on('open', () => {
        // Handshake initiated; waiting for confirmation string
      });

      this.ws.on('message', (data) => {
        const messageText = data.toString('utf-8');

        // Check for server connection confirmation
        if (messageText.includes('Connected to WebSocket server')) {
          this.isConnected = true;
          return resolve();
        }

        try {
          const payload = JSON.parse(messageText);
          this.handlePayload(payload);
        } catch (err) {
          console.error('[Voicemaker] Unrecognized non-JSON message:', messageText);
        }
      });

      this.ws.on('error', (err) => {
        console.error('[Voicemaker WS Error]', err);
        if (!this.isConnected) reject(err);
      });

      this.ws.on('close', (code, reason) => {
        this.isConnected = false;
        console.warn(`[Voicemaker WS Closed] code: ${code}, reason: ${reason}`);
      });
    });
  }

  // 2. Dispatch audio chunk callbacks to the active stream handler
  handlePayload(payload) {
    if (!payload.success) {
      console.error('[Voicemaker TTS Failure]', payload.message, payload.errors);
      return;
    }

    if (payload.audio) {
      const audioBuffer = Buffer.from(payload.audio, 'base64');
      const isFinal = Boolean(payload.isFinal);

      // Invoke listener registered for the current conversion
      if (this.currentChunkHandler) {
        this.currentChunkHandler(audioBuffer, isFinal);
      }
    }
  }

  // 3. Send text chunk using ProPlus Turbo engine
  synthesizeChunk(text, onAudioChunk, voiceConfig = {}) {
    if (!this.isConnected) {
      throw new Error('WebSocket is not connected to Voicemaker.');
    }

    this.currentChunkHandler = onAudioChunk;

    const requestPayload = {
      VoiceId: voiceConfig.voiceId || 'ai3-Jony',
      LanguageCode: voiceConfig.languageCode || 'en-US',
      Text: text,
      ProEngine: 'turbo', // Directs request to ProPlus Turbo engine
      Engine: 'neural',
      OutputFormat: voiceConfig.outputFormat || 'mp3',
      SampleRate: voiceConfig.sampleRate || '48000',
      MasterSpeed: '0',
      MasterVolume: '0',
      MasterPitch: '0',
    };

    this.ws.send(JSON.stringify(requestPayload));
  }

  close() {
    if (this.ws) {
      // Note: Sending an empty message or {} instructs Voicemaker server to close
      this.ws.send('{}');
      this.ws.close();
    }
  }
}

// 4. Voice Agent Sentence-Boundary Buffer
class AgentSentenceBuffer {
  constructor(onSentenceReady) {
    this.buffer = '';
    this.onSentenceReady = onSentenceReady;
    // Split on punctuation followed by space or end of token
    this.sentenceRegex = /([.?!;]+)(\s|$)/;
  }

  pushToken(token) {
    this.buffer += token;
    let match;
    while ((match = this.sentenceRegex.exec(this.buffer)) !== null) {
      const splitPoint = match.index + match[1].length;
      const sentence = this.buffer.slice(0, splitPoint).trim();
      this.buffer = this.buffer.slice(splitPoint).trimStart();

      if (sentence.length > 0) {
        this.onSentenceReady(sentence);
      }
    }
  }

  flush() {
    if (this.buffer.trim().length > 0) {
      this.onSentenceReady(this.buffer.trim());
      this.buffer = '';
    }
  }
}

// Example usage:
(async () => {
  const tts = new VoicemakerTTSStreamer(process.env.VOICEMAKER_API_KEY);
  await tts.connect();
  console.log('Connected to Voicemaker WebSocket API.');

  const buffer = new AgentSentenceBuffer((sentence) => {
    console.log(`[Buffer Flush -> TTS]: "${sentence}"`);
    tts.synthesizeChunk(sentence, (chunk, isFinal) => {
      console.log(`Received audio chunk: ${chunk.length} bytes (isFinal: ${isFinal})`);
      // Pipe chunk into audio player buffer / WebRTC AudioTrack here
    });
  });

  // Simulate streaming tokens from an LLM
  const llmTokens = ['Hello! ', 'I am ', 'your AI assistant, ', 'powered by ', 'Voicemaker ProPlus Turbo. ', 'How can I assist you?'];
  for (const token of llmTokens) {
    buffer.pushToken(token);
    await new Promise((r) => setTimeout(r, 60)); // 60ms inter-token delay
  }
  buffer.flush();
})();

5. Production Considerations and Latency Optimization

Managing the 1-Minute Inactivity Timeout

Voicemaker automatically terminates WebSocket connections after 60 seconds of inactivity. When closed by timeout, it returns:

{ "success": false, "message": "Connection timeout: No message received for one minute" }

Model Selection: Why 365Finds Prefers ProPlus Turbo

Voicemaker offers several engine tiers:

Engine FamilyLatency TierCharacter Cost MultiplierBest Suited For
ProPlus Turbo~250–300 ms2×Interactive Voice Agents, Chatbots, Real-time IVR
ProPlus High-Res~800–1,500 ms4×Podcast production, Commercial ads, Video dubbing
ProPlus Expressive~1,000–2,000 ms4×Creative storytelling, Dramatic audiobook narration
Pro1 / Default~400–600 ms1×Bulk asynchronous synthesis, notification readouts

For dialogue systems, ProPlus Expressive and High-Res produce superior cinematic inflections but introduce unacceptable latency penalties. ProPlus Turbo maintains 30+ supported languages and natural prosody while cutting latency by over 60%, delivering conversational fluidness without ballooning credit expenses.

Handling User Barge-In (Interruption)

In full-duplex conversational voice bots:

  1. When client-side Voice Activity Detection (VAD) registers user speech while the agent is speaking, trigger an immediate client cancellation event.
  2. Flush the client audio playback queue to stop audio instantly.
  3. Drop pending in-flight audio chunks from the Voicemaker WebSocket handler for the cancelled turn. There is no need to reconnect the socket—simply ignore remaining chunks marked for the obsolete request ID.

References