we have an agent running on node and we want to gi...
# ask-ai
h
we have an agent running on node and we want to give our client. the ability to puse and resume live voice generation what is the best way to achive this. the voice must be real generated and the app can stop the voice player and resume it on command
t
Thanks for reaching out, Gabriel. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're asking how to let your client pause and resume live, real-time generated voice from a Node agent while controlling playback. The simplest, reliable pattern is: stop synthesis with a SpeechHandle interrupt when the user pauses, then resume by re-generating the remaining audio (using preserved context). Steps: 1. Start speech and save the returned
SpeechHandle
. ◦ Use
session.say()
or
session.generateReply()
to begin TTS and store the handle. 1. Pause: call
handle.interrupt()
. ◦ This immediately stops synthesis and playback. 1. Preserve state for resuming: ◦ Track where playback stopped (e.g., last completed sentence/word index or timestamp). ◦ Save the LLM/context used so you can continue from the same point. 1. Resume: re-generate the remaining content. ◦ Call
session.generateReply()
or
session.say()
with instructions like “continue from where you left off” or with the remaining text chunk. ◦ If content is static, send the remaining text directly; if dynamic, pass the saved LLM context so it continues naturally. Implementation tips: • Break long responses into sentence/chunk-sized pieces so interruption + resume feels seamless. • Use a realtime-capable TTS plugin (ElevenLabs, OpenAI, Cartesia, etc.) for low latency streaming. • Consider preemptive generation or keeping short lookahead buffers to reduce restart latency. • Optionally play a short “thinking” or hold sound during the pause to improve UX. If you want, share a short code snippet of how you call
session.generateReply()
now and how you track playback; I’ll suggest exact changes to store the
SpeechHandle
, track resume points, and re-trigger generation. Sources: Agent speech and audio | LiveKit docs | Agents (Node.js) | livekit/livekit_composite | DeepWiki | Text-to-speech (TTS) models | LiveKit Docs | Live Conversations with AI using ChatGPT and WebRTC
h
suggest example how to store the
SpeechHandle
, track resume points, and re-trigger generation.
t
Responding to your request for an example that stores the
SpeechHandle
, tracks resume points, and re-triggers generation in a Node.js LiveKit agent. Below is a concise, practical TypeScript example showing: • store/interrupt a
SpeechHandle
• track progress by sentence chunks (resume points) • resume by re-generating the remaining text
Copy code
// resumable-agent.ts
import { voice } from "@livekit/agents";

type SpeechState = {
  handle: voice.SpeechHandle | null;
  chunks: string[];        // pre-split text chunks (sentences)
  currentIndex: number;    // index of next chunk to speak
};

export class ResumableAgent extends voice.Agent {
  private state: SpeechState = { handle: null, chunks: [], currentIndex: 0 };

  // Split into chunks (simple sentence splitter — adjust for your needs)
  private splitIntoChunks(text: string): string[] {
    return text
      .split(/(?<=[.!?])\s+/)    // keeps punctuation with chunk
      .map(s => s.trim())
      .filter(Boolean);
  }

  // Start a new speech session from beginning
  async startSpeech(text: string) {
    this.state.chunks = this.splitIntoChunks(text);
    this.state.currentIndex = 0;
    await this.playNextChunk();
  }

  // Play the next chunk and store the handle
  private async playNextChunk() {
    const { chunks, currentIndex } = this.state;
    if (currentIndex >= chunks.length) {
      this.state.handle = null;
      return; // finished
    }

    const textToSpeak = chunks[currentIndex];

    // begin TTS and store handle
    this.state.handle = this.session.generateReply({
      userInput: textToSpeak,
    });

    try {
      await this.state.handle; // resolves when chunk finishes or is interrupted
      // if finished normally, advance to next chunk and auto-play it
      if (!this.state.handle?.interrupted) {
        this.state.currentIndex += 1;
        await this.playNextChunk();
      }
    } catch (err) {
      // handle was interrupted or errored — leave currentIndex as-is for resume
      // optionally log err
    }
  }

  // Pause: interrupt current handle
  pauseSpeech() {
    const h = this.state.handle;
    if (h && !h.interrupted) {
      h.interrupt(); // stops playback and synthesis
    }
  }

  // Resume: play from currentIndex
  async resumeSpeech() {
    if (this.state.currentIndex < this.state.chunks.length && !this.state.handle) {
      await this.playNextChunk();
    }
  }

  // Optional: jump to a specific chunk index (useful for seeking)
  async seekToChunk(index: number) {
    if (index < 0 || index >= this.state.chunks.length) return;
    // interrupt current if playing
    if (this.state.handle && !this.state.handle.interrupted) this.state.handle.interrupt();
    this.state.currentIndex = index;
    await this.playNextChunk();
  }
}
Quick notes: • We chunk by sentence so resuming restarts at the next sentence boundary; this makes interruption/resume feel natural. •
SpeechHandle
cannot be resumed inline — you interrupt and re-generate the remaining chunk(s). • For finer-grained resumes, split into smaller chunks (phrases/words) and update
currentIndex
accordingly. • Use realtime-capable TTS providers (ElevenLabs, OpenAI, Cartesia, etc.) for low-latency streaming. If you want, share a sample of your current
generateReply()
call and I’ll adapt this example to fit your existing code and chunking preferences. Sources: Agent speech and audio | LiveKit docs