All posts
Tutorial

Add Gradium's Phonon Text-to-Speech to Your Android App

Make an Android app speak offline with Gradium's Phonon and the Xybrid SDK: Gradle setup, Kotlin and React Native code, voices, streaming and limits.

Phonon is Gradium’s open-weight text-to-speech model. Its English checkpoint, phonon-31m-en, runs on an Android phone’s CPU through the standard Xybrid package, and after a one-time 74 MB download it needs no network connection.

Gradium’s Phonon on Xybrid introduces the model and how we brought it to Xybrid. This guide is the Android code: setup, synthesis, playback, voices, streaming, and the limits to plan around.

Phonon is in the standard Kotlin package from Xybrid 0.16.0, on arm64-v8a devices running Android 10 (API 29) or later. React Native uses the same package on Android.

1. Add the dependency

// app/build.gradle.kts
android {
    defaultConfig {
        minSdk = 29 // Xybrid 0.16.0 and later need Android 10
    }
}

dependencies {
    implementation("ai.xybrid:xybrid-kotlin:0.20.0")
    implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.7.0")
}

Then check three things:

  • Network permission. The SDK downloads the model from the registry and declares no permissions itself, so add <uses-permission android:name="android.permission.INTERNET" /> to your manifest.
  • The arm64-v8a ABI. Only the arm64-v8a library contains the speech engine. If you restrict ABIs with abiFilters or App Bundle splits, keep it. On armeabi-v7a and x86_64 devices, and on x86_64 emulator images, the registry doesn’t serve Phonon. Arm64 emulator images, such as those on Apple Silicon Macs, do run it.
  • R8 rules. If your release build shrinks code with R8 (isMinifyEnabled = true, enableProguardInReleaseBuilds = true in a React Native app, or an Expo SDK 58 release build, which shrinks by default), add the rules below to proguard-rules.pro. In an Expo app, pass them as android.extraProguardRules to expo-build-properties instead, so expo prebuild doesn’t overwrite them. No published release ships these rules yet, and without them the SDK fails to load in a minified build.
-keep class ai.xybrid.Native {
    native <methods>;
    static void boltffiFutureContinuationCallback(long, byte);
}
-keep class ai.xybrid.BoltFfiErrorBufferException {
    <init>(byte[]);
}

2. Load Phonon and synthesize

Call Xybrid.init(this) in your Application.onCreate() override to set up the model cache. If you create the subclass below, set android:name=".MyApplication" on your manifest’s <application> element.

import android.app.Application
import ai.xybrid.Xybrid

class MyApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        Xybrid.init(this)
    }
}

Load one model for the screen or service that needs speech, then pass that model to each synthesis request. The first load downloads one 74,446,144-byte file, checks its SHA-256 and caches it in the app’s files directory. Later loads use the cached copy offline.

import ai.xybrid.Envelope
import ai.xybrid.XybridModel
import ai.xybrid.audioBytes
import ai.xybrid.runAsync

suspend fun synthesize(phonon: XybridModel, text: String): ByteArray {
    val result = phonon.runAsync(Envelope.text(text, voiceId = "easton"))
    val status = result.envelope.metadata.firstOrNull { it.key == "tts_status" }?.value
    check(status == "completed") { "Phonon synthesis did not complete ($status)" }
    return result.audioBytes?.takeIf { it.isNotEmpty() } ?: error("Phonon returned no audio")
}

If a sentence exceeds 256 tokens, Xybrid 0.20.0 returns limited with an empty byte array or audio from earlier sentences. A completed request returns 16-bit little-endian mono samples at 24 kHz.

3. Play it

Use one AudioTrack per response. Wait for its playback head to reach the last frame, then release the track. The coroutine below keeps the model loaded across requests and calls phonon.close() when the flow ends or the coroutine is cancelled.

import android.media.AudioAttributes
import android.media.AudioFormat
import android.media.AudioTrack
import ai.xybrid.Xybrid
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.withContext

suspend fun speakRequests(requests: Flow<String>) = withContext(Dispatchers.IO) {
    val phonon = Xybrid.model("phonon-31m-en").loadBlocking()
    try {
        requests.collect { text ->
            val pcm = synthesize(phonon, text)
            val track = play(pcm)
            try {
                val frameCount = pcm.size / 2 // Two bytes per mono PCM16 frame.
                while (track.playbackHeadPosition < frameCount) {
                    delay(20)
                }
            } finally {
                track.release()
            }
        }
    } finally {
        phonon.close()
    }
}

fun play(pcm: ByteArray): AudioTrack {
    val track = AudioTrack.Builder()
        .setAudioAttributes(
            AudioAttributes.Builder()
                .setUsage(AudioAttributes.USAGE_MEDIA)
                .setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
                .build()
        )
        .setAudioFormat(
            AudioFormat.Builder()
                .setEncoding(AudioFormat.ENCODING_PCM_16BIT)
                .setSampleRate(24_000)
                .setChannelMask(AudioFormat.CHANNEL_OUT_MONO)
                .build()
        )
        .setBufferSizeInBytes(pcm.size)
        .setTransferMode(AudioTrack.MODE_STATIC)
        .build()
    try {
        check(track.write(pcm, 0, pcm.size) == pcm.size) { "Could not write all PCM samples" }
        track.play()
        return track
    } catch (error: Exception) {
        track.release()
        throw error
    }
}

In a ComponentActivity or AppCompatActivity, launch the function from onCreate() using AndroidX’s lifecycleScope. For requests from your UI, pass the screen’s Flow<String> in place of flowOf(...).

// Inside onCreate(). Imports: androidx.lifecycle.lifecycleScope,
// kotlinx.coroutines.flow.flowOf and kotlinx.coroutines.launch.
lifecycleScope.launch {
    speakRequests(flowOf("Your table is ready. Please come to the front desk."))
}

React Native

On Android, @xybrid/react-native wraps the same Kotlin package. Use React Native 0.76 or later with the New Architecture, or an Expo development build on SDK 52 or later. Set the Android minSdkVersion to 29, through expo-build-properties in an Expo app.

pnpm add @xybrid/[email protected]

Rebuild your Android app with pnpm exec react-native run-android or, for Expo, pnpm exec expo run:android to link the native package. Run it on an arm64-v8a device or emulator.

Pass an array to speak a batch or an async iterable to keep the same model loaded as requests arrive. Supply your own playPcm function to decode the base64 and play raw 24 kHz mono PCM16 little-endian audio.

import { Envelope, ModelLoader } from '@xybrid/react-native';

async function speakRequests(
  requests: Iterable<string> | AsyncIterable<string>,
  playPcm: (audioBase64: string) => Promise<void>,
) {
  const phonon = await ModelLoader.fromRegistry('phonon-31m-en').load();
  try {
    for await (const text of requests) {
      const result = await phonon.run(Envelope.text(text, { voiceId: 'easton' }));
      const status = result.envelope.metadata?.tts_status;
      if (status !== 'completed') {
        throw new Error(`Phonon synthesis did not complete (${status})`);
      }
      if (!result.audioBytesBase64) throw new Error('Phonon returned no audio');
      await playPcm(result.audioBytesBase64);
    }
  } finally {
    await phonon.release();
  }
}

Choose a voice

phonon-31m-en holds Gradium’s 37 English catalog voices, plus default, the voice the checkpoint shipped with on October 20. Pass a name as voiceId; without one, Phonon uses default.

GroupVoices
US Englishdelia, everly, hadley, harper, juniper, zoey, easton, micah, miles, preston, russell, trevor
British Englishbryony, elodie_rose, freya, imogen, lottie, maeve, pippa, alfie, edwin, hugh, spencer, teddy, toby
Charactersazgorath, captain_silas_blackwater, fairy_godmother, fennick_the_young_elf, grub_the_ogre, master_aldric, morwenna_of_the_deep, old_mortlake, sir_bramwell, the_snow_queen, the_thing_under_the_stairs, vyrmathrax_the_ancient

The character voices suit games and storytelling. Gradium’s voice catalog on Hugging Face has a sample of every voice. For Phonon, the SDK’s voices() returns an empty list and voice(id) returns null, so keep the names in your app and don’t validate them against those calls. Gradium has since changed the checkpoint’s default voice on Hugging Face; Xybrid’s default is the earlier one.

Streaming and interruption

runAsync returns audio when batch synthesis ends. To start playback sooner, use streaming. Phonon generates audio in 80 ms frames, and Xybrid passes audio to your app while synthesis runs.

  • Kotlin. Call runStream, then call streamNext in a loop off the main thread, since it blocks. Each AUDIO event carries 24 kHz PCM16 to write to an AudioTrack in MODE_STREAM, until a COMPLETE event arrives. Then call streamClose (or streamResult) to release the stream; calling streamClose earlier stops the run. The streamTokens Flow doesn’t carry audio.
  • React Native. runTtsStreaming is an async generator of audio chunks. Stop it with an AbortSignal or by breaking out of the loop.

Stopping a stream stops synthesis, but audio already delivered stays delivered. When the user interrupts, clear your own playback queue too.

What Phonon needs from the device

phonon-31m-en through the Xybrid Android SDK
Download and storageOne 74 MB file (74,446,144 bytes) with the weights, tokenizer and all 38 voices
MemoryThe file is memory-mapped rather than copied, and its pages count toward your app’s memory as the engine reads them. Total runtime memory isn’t measured yet
DeviceAndroid 10 (API 29) or later, arm64-v8a
ComputeCPU only, one thread through the SDK. No GPU or NPU needed
Output24 kHz mono, 16-bit PCM
NetworkOnly for the first download

We haven’t published speed or latency measurements for phonon-31m-en through the SDK on a phone yet, so this guide doesn’t quote any. When we do, they’ll name the device, the thread count and exactly what was timed. Until then, measure on the slowest device you support, with the streaming API. Time two things: from your call to the first audio your app receives, and from your call to the first sample your user hears through your audio path. They differ, and users notice the second.

Warm up the voice. When the engine opens a session, it computes the voice’s prefix once and reuses it for every sentence. Xybrid keeps the session open between requests while the voice and sampling settings stay the same, and opens a new one when they change. The session opens on the first run, not at load(). To keep that cost off the first real request, synthesize a short sentence with your chosen voice while your UI loads.

Limits to know

  • English only. Other language settings change only how text is normalized, not pronunciation. Gradium’s 40M models (English, French, German, Spanish, Portuguese and a multilingual model) are licensed CC BY-NC 4.0 and aren’t in the Xybrid registry.
  • Android arm64 only, for now. The standard iOS, Flutter, Unity and desktop packages don’t include the speech engine yet. On those platforms, use Gradium’s ptts.
  • Keep each sentence short. The engine splits text at sentence ends. Split sentences longer than 256 tokens (word pieces from Phonon’s tokenizer) before synthesis. If you get tts_status: limited, skip playback and retry with shorter sentences.
  • Partial text normalization. Numbers, currency, emails, URLs and common abbreviations are expanded. Dates and times get no special reading, and phone numbers are read in groups only when their digits are joined by dashes (555-123-4567). Write other formats out if pronunciation matters.
  • No speaking-rate control, phoneme timings or custom voices through the SDK. Phonon ignores the speed argument of Envelope.text, and the SDK can’t load voice files from outside the model file.

Licenses and attribution

  • The model. Phonon 31M’s weights, tokenizer and voices are Apache-2.0, from Gradium, and build on Kyutai’s Pocket TTS and Mimi codec. Gradium asks that Phonon not be used to impersonate real people, deceive listeners or clone voices without consent, and that you tell listeners when speech is synthetic where that matters to them.
  • The engine. The speech engine inside the Android package isn’t open source. Its runtime terms let you use it through the SDK and ship it in your app, commercial apps included. The package carries those terms and the third-party notices (14 files under assets/xybrid/zzz/), and Android merges them into your APK, so don’t strip them.

Next steps

  1. Read the SDK documentation for the rest of the Android API. Kotlin README · React Native README
  2. Read Gradium’s model card and listen to the voice catalog.

Building a full voice loop? Building a Voice Agent That Runs Entirely On-Device covers speech recognition, a local LLM and text-to-speech together.

FAQ

Does Phonon work offline on Android?

Yes, after the first download. The SDK caches the model file, later loads don’t contact the registry, and synthesis runs on the device’s CPU.

Is Phonon free for commercial use?

phonon-31m-en, the checkpoint Xybrid serves, is Apache-2.0, which allows commercial use. The speech engine that runs it in the Xybrid Android package isn’t open source, but its runtime terms let you ship it in commercial apps as long as you keep its notices. Gradium’s 40M models are CC BY-NC and aren’t in the Xybrid registry.

Can I clone a voice or add my own?

Not through the Xybrid SDK, which only uses the voices inside its model file. Gradium creates cloned and designed voices through its own API, and ptts plays those voice files on the device. The Xybrid SDK can’t load them yet.

Does Phonon speak languages other than English?

phonon-31m-en speaks English only. Gradium’s 40M models cover French, German, Spanish and Portuguese, but their CC BY-NC license rules out commercial use without a separate license from Gradium, and Xybrid doesn’t serve them.

All posts