◉RORK LABJP
●SUBDOMAIN — Rork can now connect your web app to a subdomain only, leaving your root domain and www untouched (12/1)●UPDATES — expo-updates 58.0.23 fixes Android release builds embedding a stale runtime version●FLASH END — Intro pricing for Gemini Flash models ends 12/31, 29 days from now. Time to recheck AI feature costs●HMR — Some report the dev server picking up another server's bundle and then exiting●FIRST VIEW — Map the first screen for a normal launch, a notification, and a link, and back navigation stops surprising you●CARBON — Gemini 4 Carbon and Argon are now at standard rates: $4.00 input, $20.00 output per 1M tokens●SUBDOMAIN — Rork can now connect your web app to a subdomain only, leaving your root domain and www untouched (12/1)●UPDATES — expo-updates 58.0.23 fixes Android release builds embedding a stale runtime version●FLASH END — Intro pricing for Gemini Flash models ends 12/31, 29 days from now. Time to recheck AI feature costs●HMR — Some report the dev server picking up another server's bundle and then exiting●FIRST VIEW — Map the first screen for a normal launch, a notification, and a link, and back navigation stops surprising you●CARBON — Gemini 4 Carbon and Argon are now at standard rates: $4.00 input, $20.00 output per 1M tokens
Articles/AI Models
◉ AI Models/2026-04-29Intermediate

Building a Talking AI Companion App with Rork and ElevenLabs

Text-only companion apps are easy to launch once and then forget. Adding a real voice through ElevenLabs changes the experience entirely. Here's a hands-on guide to wiring it up in a Rork app, with caching tactics and paywall design that actually work.

Rork622ElevenLabsVoice AIAI CompanionIndie Dev40

I used to check the analytics for my TestFlight builds every couple of days, and the text-only companion app always told the same story: a few days after people got it, the launches thinned out fast. I've heard similar things about the genre, but retention numbers shift with how they're counted, so I'll stick to what I saw in my own builds.

What changed that was adding ElevenLabs voice synthesis so the character actually speaks back. Same response text, but with a voice attached, sessions got visibly longer and more people started the trial. This guide walks through how to plug ElevenLabs into a Rork-built app, and the small operational tricks that keep cost and quality manageable over time.

Why Text-Only Companions Stop Sticking

My first companion app used Claude for text and rendered the responses in a chat bubble. The most common piece of feedback was: "How is this different from ChatGPT?" Fair question — text chat is already a solved interface, dominated by major players.

Once I added voice, the change wasn't only in the metrics; it was in how people used the app:

  • Some people began keeping it on the bedside table to talk to before sleep
  • Commute-time use showed up, with people listening through earbuds without looking at the screen
  • Reviews started mentioning specific moments — "she called me by my name" — that text alone never produced

In other words, voice unlocks the off-screen moments. Rork lets you assemble the UI quickly, and ElevenLabs gives you natural multilingual speech via API, so an indie dev can ship this experience in roughly a week.

Why ElevenLabs (vs. OpenAI TTS or Google Cloud TTS)

Several TTS APIs exist. I paid for the major ones and ended up choosing ElevenLabs for companion-style apps. Pricing and model names change every few months, so treat the figures below as a snapshot from the time of writing and check each vendor's official page before you commit.

  • Naturalness in non-English: ElevenLabs Multilingual v2 held intonation well even in long sentences with mixed scripts. OpenAI TTS was fluent but a bit flat to my ear; Google's WaveNet voices felt monotone at sentence endings
  • Character expressiveness: ElevenLabs Voice Design lets you create new voices from a text prompt ("warm, slightly low, calm"). OpenAI gives you six fixed voices; Google offers gender and age variations only
  • Latency: ElevenLabs Flash v2.5 returns the first audio chunk in roughly 75ms according to ElevenLabs' own documentation. The others tend to land in the hundreds of milliseconds, and for real-time conversation the Flash difference is noticeable — though your network will move these numbers around
  • Cost: ElevenLabs has higher per-character pricing (as a rough guide at the time of writing: Creator plan $22/mo for 100k characters, around $0.30 per 1k after). With caching, ongoing cost is workable

If your top priorities are character voices and natural multilingual speech, ElevenLabs wins. If you want the cheapest path, OpenAI TTS is the pragmatic choice. That's the split I've landed on, and here is the short version as a table.

What you can't compromise onWhere I'd startWhat to check before paying
Character in the voiceElevenLabs (Voice Design)Per-character price and the monthly cap
Natural intonation in JapaneseElevenLabsWhether long lines get misread
Keeping monthly cost lowOpenAI TTSWhether the fixed voices fit your world
Staying inside an existing Google Cloud setupGoogle Cloud TTSWhether sentence endings suit the character

The right-hand column is what I check by reading about ten of my own scripts through the service before subscribing. I once chose on the strength of a short sample, then found misreadings the moment a long line went through, and had to choose again. Judge a voice on your own script, not on the vendor's sample. That's the line I hold now.

One thing worth flagging: model lineups and pricing in this space move quickly. If you tested ElevenLabs a while ago and set it aside for cost or latency reasons, it may be worth listening again — the Flash family in particular was built with real-time conversation in mind. I may be missing recent changes on the other vendors' side too, so compare on the same day.

Overall Architecture

The companion app we'll build follows this flow:

  1. User speaks (or types) a message
  2. Whisper or OpenAI Realtime API converts speech to text
  3. Claude or GPT generates a response
  4. Response text goes to ElevenLabs and returns as audio
  5. App plays the audio with a synced caption

Rork-side: React Native / Expo, Zustand for state, expo-av for playback. Backend: a small Cloudflare Worker that proxies ElevenLabs so the API key never lands in the app bundle.

There are two design choices worth calling out before we get into code. First, we're treating the LLM (Claude/GPT) and TTS (ElevenLabs) as two independent calls rather than a single multimodal pipeline. This adds one network hop, but in practice it makes the app dramatically easier to debug — you can verify the LLM output as plain text before paying for synthesis, and you can swap either component without rewriting the other. Second, the Worker is intentionally thin. It does authentication, calls ElevenLabs, and streams the bytes back. Anything stateful (user usage counts, cache lookups) is added in later layers, so we can ship the smallest correct version first.

Getting an ElevenLabs Key (and Storing It Safely)

Sign up at ElevenLabs and generate an API key. Three things to keep in mind:

  • Keep the key out of the app. It's easy to extract from a shipped bundle, so proxy through a backend
  • Keep the Voice ID out of logs. The ID alone doesn't let a stranger synthesize speech, but if your API key ever leaks it tells them which voices are available. For cloned voices in particular, I keep the ID out of logs and out of the app
  • Set usage alerts right away. In the dashboard's Usage tab, add an 80% monthly threshold alert

I skipped that last one at first. A loop bug during debugging used up a month's character budget overnight, and I still remember the knot in my stomach when the billing email arrived the next morning.

A Cloudflare Worker Proxy

We'll route TTS calls through Cloudflare Workers so the ElevenLabs key stays server-side and we get a natural place to add caching and rate limiting later.

// worker/src/index.ts — ElevenLabs proxy
// Purpose: take text from the client, return audio bytes from ElevenLabs.
// Why proxy: keep API key off-device, and gain a layer for caching/rate limiting.
 
export interface Env {
  ELEVENLABS_API_KEY: string;
  ELEVENLABS_VOICE_ID: string;
  AUTH_SECRET: string;
}
 
export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    if (request.method !== "POST") {
      return new Response("Method Not Allowed", { status: 405 });
    }
 
    // 1. Verify the request came from our app (use a real JWT in production)
    const auth = request.headers.get("Authorization");
    if (auth !== `Bearer ${env.AUTH_SECRET}`) {
      return new Response("Unauthorized", { status: 401 });
    }
 
    // 2. Parse the request body
    const { text, modelId = "eleven_flash_v2_5" } = await request.json<{
      text: string;
      modelId?: string;
    }>();
 
    if (!text || text.length > 1000) {
      return new Response("Invalid text length", { status: 400 });
    }
 
    // 3. Call ElevenLabs and pass through the audio body
    const elevenRes = await fetch(
      `https://api.elevenlabs.io/v1/text-to-speech/${env.ELEVENLABS_VOICE_ID}`,
      {
        method: "POST",
        headers: {
          "xi-api-key": env.ELEVENLABS_API_KEY,
          "Content-Type": "application/json",
          "Accept": "audio/mpeg",
        },
        body: JSON.stringify({
          text,
          model_id: modelId,
          voice_settings: {
            stability: 0.5,        // balance between expressiveness and stability
            similarity_boost: 0.75, // closeness to the source voice
            style: 0.3,            // character intensity (too high adds noise)
            use_speaker_boost: true,
          },
        }),
      }
    );
 
    if (!elevenRes.ok) {
      const errText = await elevenRes.text();
      console.error("ElevenLabs error:", elevenRes.status, errText);
      return new Response("TTS upstream error", { status: 502 });
    }
 
    // 4. Stream the MP3 back to the client (expo-av will play it)
    return new Response(elevenRes.body, {
      headers: {
        "Content-Type": "audio/mpeg",
        "Cache-Control": "private, no-store", // reuse happens in the cache layers below
      },
    });
  },
};

Marking an authenticated response Cache-Control: public opens the door to it landing in a shared cache. I leave reuse to the caching layers described later and send no-store from this Worker.

AUTH_SECRET is only a stand-in for testing. The hook below reads it from an EXPO_PUBLIC_ variable, and anything with that prefix ends up inside the app bundle where it can be extracted — so a fixed string only honors half of the "no secrets in the app" rule. In production, have the Worker verify a per-user JWT (Sign in with Apple, Firebase Auth, etc.) and add rate limiting. Expected behavior: POST text in, MP3 bytes streaming back within a few hundred milliseconds.

A Reusable Hook for the Rork App

Wrapping playback in a custom hook keeps screen code clean and avoids the most common mistake — doubled audio when users tap fast. The hook below uses expo-av, but Expo has been steering people toward expo-audio; for a new app, check your Expo SDK's documentation for the current recommendation first. The idea (release the previous sound, fail silently) is the same either way.

// hooks/useVoiceResponse.ts — play ElevenLabs audio for response text
// Solves: duplicate playback, loading state, silent fallback on error
 
import { useState, useRef, useCallback } from "react";
import { Audio } from "expo-av";
import * as FileSystem from "expo-file-system";
 
const PROXY_URL = process.env.EXPO_PUBLIC_TTS_PROXY_URL!;
const AUTH_SECRET = process.env.EXPO_PUBLIC_TTS_AUTH_SECRET!;
 
export function useVoiceResponse() {
  const [isPlaying, setIsPlaying] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const soundRef = useRef<Audio.Sound | null>(null);
 
  const speak = useCallback(async (text: string) => {
    if (!text.trim()) return;
    // Stop anything currently playing (overlapping voices feel broken)
    if (soundRef.current) {
      await soundRef.current.unloadAsync();
      soundRef.current = null;
    }
 
    setIsLoading(true);
    try {
      const res = await fetch(PROXY_URL, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "Authorization": `Bearer ${AUTH_SECRET}`,
        },
        body: JSON.stringify({ text }),
      });
 
      if (!res.ok) throw new Error(`TTS HTTP ${res.status}`);
 
      // Save to a file (expo-av is much more reliable loading from a URI)
      const blob = await res.blob();
      const reader = new FileReader();
      const base64 = await new Promise<string>((resolve, reject) => {
        reader.onload = () => resolve((reader.result as string).split(",")[1]);
        reader.onerror = reject;
        reader.readAsDataURL(blob);
      });
 
      const fileUri = `${FileSystem.cacheDirectory}voice_${Date.now()}.mp3`;
      await FileSystem.writeAsStringAsync(fileUri, base64, {
        encoding: FileSystem.EncodingType.Base64,
      });
 
      const { sound } = await Audio.Sound.createAsync(
        { uri: fileUri },
        { shouldPlay: true }
      );
      soundRef.current = sound;
      setIsPlaying(true);
 
      sound.setOnPlaybackStatusUpdate((status) => {
        if (status.isLoaded && status.didJustFinish) {
          setIsPlaying(false);
          sound.unloadAsync();
        }
      });
    } catch (err) {
      console.error("TTS playback failed:", err);
      // Silent fallback — keep the chat experience going via text only
    } finally {
      setIsLoading(false);
    }
  }, []);
 
  const stop = useCallback(async () => {
    if (soundRef.current) {
      await soundRef.current.stopAsync();
      await soundRef.current.unloadAsync();
      soundRef.current = null;
      setIsPlaying(false);
    }
  }, []);
 
  return { speak, stop, isPlaying, isLoading };
}

A small but critical detail: Audio.Sound instances must be unloaded when finished. When I skipped unloadAsync, memory kept growing and the app dropped out after a few minutes of conversation on a real device. I hit this three times before I learned to write the cleanup first — the simulator rarely shows it. Release leaks aren't unique to the older API either; the story of expo-audio's createAudioPlayer going silent around the 40th play is a good companion read.

Cutting Cost with Layered Caching

ElevenLabs charges by character, so naive usage scales linearly with active users. A three-layer cache cut my running cost noticeably (how much depends on how many of your lines are repeatable):

  • Local file cache on the client. Keep the most recent 100 phrases per user. Greetings ("good morning," "thank you") hit here and never touch the network
  • Cloudflare KV cache. SHA-256 of the text as the key, audio URL as the value. Onboarding lines and error prompts are shared across all users, so this is a high-hit layer
  • Cloudflare R2 for audio files. KV holds only metadata; the MP3 bytes live in R2 with a 30-day TTL

Implementation order matters: deploy KV first and watch hit rates before adding the local layer or R2. When I built all three at once, I could no longer tell which layer was helping and which was serving stale audio, and I ended up staring at the logs for an evening.

A small note on cache key design: don't hash the raw text directly. Normalize it first — lowercase, trim whitespace, collapse repeated punctuation. Without normalization, "Good morning!" and "good morning" land in different buckets and you waste both money and storage. I also strip user-specific tokens (names, dates) before hashing for shared phrases, so the user's actual name is interpolated client-side after playback.

Pairing with the Paywall

Voice usage is the perfect feature to gate behind a subscription, because the value is felt on every interaction. The structure that converted most naturally for me:

PlanVoice playbackAdded features
FreeUp to 10 per dayText chat stays unlimited
Pro (monthly)UnlimitedCharacter switching (multiple Voice IDs)
Premium (one-time)UnlimitedCustom voice creation via ElevenLabs Voice Design

The figure of ten per day is a placeholder I picked. In an app with long replies, ten plays can already be plenty; in one built on short back-and-forth, it may feel stingy. Look at the average length of a single reply in your own app before settling on a number.

Keeping text unlimited and only gating voice preserves the core experience while opening a clean upgrade path. Combine this with the RevenueCat subscription guide for Rork and you can have monetization wired in within the same week.

Three Pre-Launch Checks You Can't Skip

I shipped without these once and had to push three patch releases.

  • iOS silent mode playback. Call Audio.setAudioModeAsync({ playsInSilentModeIOS: true }) on app launch; otherwise the app falls silent in silent mode and reviewers will say it's broken
  • Bluetooth disconnect handling. AirPods plus backgrounding can cut audio, so set staysActiveInBackground: true on the audio mode
  • Long response chunking. Around 1,000 characters per request was the stable range for me. Split long Claude outputs at sentence boundaries and play them sequentially

One more subtle one: when the app comes back from background, the audio session needs to be re-activated explicitly on iOS, otherwise the next playback fails silently. Hooking into AppState and re-running Audio.setAudioModeAsync on active solves this without a single user-visible artifact.

It also helps to keep a symptom-to-cause table beside you, so a review doesn't send you hunting from scratch:

What users saySuspect firstHow to check
"There's no sound"Silent mode settingPlay with the hardware silent switch on
"It stops when I go home"Background audio settingLeave the app mid-playback and wait about 30 seconds
"Long replies cut off"Characters per requestLog the text length in the Worker
"It crashes after a while"Sound not unloadedRun ten back-and-forths and watch memory

A voice reaches people away from the screen, so the moment it fails to play is the one they notice most — that's the line I've drawn from this build. I now spend more of my time hunting for the silent cases than on adding voices.

If you want to go deeper on the voice/video stack, the WebRTC video calling guide and LiveKit voice/video agent production guide cover the next steps from here.

Start with One Voice You Actually Like

If you've read this far, the most useful next step is to spend an evening creating a single character voice in ElevenLabs Voice Design and dropping it into a Rork starter screen. The first time you hear your own character speak in the app, the gap between text-only and voice-first becomes obvious — and so does what to build next.

The Free tier covers 30,000 characters per month, which is plenty to validate that the voice is right before paying anything. Build the smallest version that works, ship it to a few friends, and iterate from there.

Share

Thank You for Reading

Rork Lab is ad-free, supported entirely by members like you. We publish practical guides daily with implementation code, benchmarks, and production-ready patterns. If you've found it useful, we'd love to have you on board.

  • ✦Copy-paste ready implementation code
  • ✦New advanced guides published daily
  • ✦$5/mo or $10 for lifetime access
View Membership →

If you found this article helpful, a small tip ($1.50) would mean a lot to us. Your support helps keep this site ad-free and covers server and hosting costs.

Related Articles

◉ AI Models2026-07-17
The Three-Minute Video That Kept Failing — Moving Rork's Gemini Uploads Off the Worker
How I rerouted video uploads to the Gemini Files API from a Cloudflare Workers relay to a direct device-to-Google path — why the 128MB isolate limit breaks the relay, how to hand out a resumable upload URL without leaking your API key, what Expo SDK 54 broke on the device side and how SDK 56's progress-aware upload task fixes it, a symptom-first troubleshooting table, and how the 20GB project ceiling and media resolution decide the bill (as of November 2026).
◉ AI Models2026-11-24
On December 1, Your App's gemini-2.5-flash Calls Get Rerouted Without an Error. How to Compare the Answers Before That Happens
From December 1, calls to gemini-2.5-flash and gemini-2.5-pro are not shut off but automatically routed to successor models. Because nothing errors out, changes in answer shape and cost are easy to miss. Here is how to find the model names in a Rork-built app, compare answers against the successor now, and decide whether to switch yourself or let the routing happen.
◉ AI Models2026-11-19
Your GPT-6 Astra Became 6.2 Overnight: Three Checks Before You Rebuild Anything
Since November 18, Rork projects that had GPT-6 Astra or GPT-6.1 Sol selected now build with the 6.2 versions at the same effort. If the answers suddenly feel different, here are three checks to run before rebuilding a screen, plus a small yardstick request for measuring the change.