Speech with adk-audio

adk-audio turns speech into text (STT) and text into speech (TTS) behind two traits, with cloud providers and on-device models on ONNX Runtime and Candle. Every provider takes and returns the same AudioFrame: 16-bit little-endian PCM with its sample rate and channel count.

Note: adk-audio is Beta (STABILITY.md): the local ONNX TTS backends are untested and the MLX backends are new, so its API may change in a minor release.

NeedUse
Transcribe a recording or a live stream, or speak a replyThis page: SttProvider, TtsProvider
A two-way spoken conversation with a model (OpenAI Realtime, Gemini Live)Realtime & Multimodal (adk-realtime)
The microphone, the speaker and turn-taking on a desktopDesktop Audio (desktop-audio)
Pipelines, DSP effects, the mixer and every typeThe crate README

Install

[dependencies]
adk-audio = "3.0.0"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }

The default features, tts and stt, compile every cloud provider. On-device models are opt-in:

[dependencies]
adk-audio = { version = "3.0.0", features = ["whisper-onnx", "chatterbox"] }
FeatureAdds
stt (default)Cloud STT: WhisperApiStt, DeepgramStt, AssemblyAiStt, GeminiStt
tts (default)Cloud TTS: ElevenLabsTts, OpenAiTts, GeminiTts, CartesiaTts
museMuseStt: Meta Muse file and realtime transcription, over adk-model (implies stt)
whisper-onnx, distil-whisper, moonshineOnnxSttProvider with the Whisper, Distil-Whisper and Moonshine recognisers on ONNX Runtime (each implies onnx)
kokoroKokoroPreprocessor and KokoroVoices for Kokoro-82M on OnnxTtsProvider; needs a system espeak-ng (implies onnx)
chatterboxChatterboxTtsProvider: voice cloning from a reference WAV (implies onnx)
qwen3-ttsQwen3TtsNativeProvider: Qwen3-TTS 0.6B and 1.7B on Candle
onnxONNX Runtime and OnnxTtsProvider; ort downloads the onnxruntime binary at build time
onnx-cuda, onnx-coremlThe CUDA and CoreML execution providers (each implies onnx)
all-onnxonnx, kokoro, chatterbox, whisper-onnx, distil-whisper, moonshine and qwen3-tts
mlxMlxSttProvider Whisper STT on Apple Silicon Metal GPU (mlx-rs, requires cmake and Xcode's Metal toolchain); MlxTtsProvider model loading (TTS inference not yet implemented)
fxDSP processors: loudness normalizer, resampler, noise suppressor, compressor, silence trimmer, pitch shifter
musicreqwest for your own MusicProvider
livekitRealtimeBridge between adk-realtime audio and adk-audio pipelines
desktop-audioMicrophone capture, speaker playback and VAD turn-taking (Desktop Audio)
allEvery feature except desktop-audio, onnx-cuda and onnx-coreml

Through the umbrella crate, audio enables adk-audio with its defaults; audio-onnx adds whisper-onnx, distil-whisper, moonshine and chatterbox; kokoro, qwen3-tts and all-onnx keep their names; audio-all enables all.

[dependencies]
adk-rust = { version = "3.0.0", features = ["audio", "audio-onnx"] }

The traits

TraitMethodsImplementations
SttProvidertranscribe(&AudioFrame, &SttOptions) -> Transcript; transcribe_stream(stream of AudioFrame, &SttOptions) -> TranscriptStream; billing()The STT providers below
TtsProvidersynthesize(&TtsRequest) -> AudioFrame; synthesize_stream(&TtsRequest) → a stream of AudioFrames; voice_catalog(); billing()The TTS providers below
AudioProcessorprocess(&AudioFrame) -> AudioFrameThe fx processors and FxChain
VadProcessoris_speech(&AudioFrame) -> bool; segment(&AudioFrame)None: the application supplies the detector
MusicProvidergenerate(&MusicRequest) -> AudioFrame; supported_genres()None: the application supplies the provider

Every method that can fail returns AudioResult<T>; a provider's failure is AudioError::Stt { provider, message } or AudioError::Tts { provider, message }, and a model that cannot be fetched is AudioError::ModelDownload { model_id, message }.

Speech to text

Providers

ProviderFeatureModeltranscribe_streamCredentials
GeminiSttsttgemini-3.8-flash; with_model sets anotherAudioError::Stt; live audio goes through the Gemini Live API in adk-realtimeGEMINI_API_KEY or GOOGLE_API_KEY
DeepgramSttsttnova-3; on the stream, SttOptions::model_hint sets anotherA WebSocket that takes 16 kHz mono PCM16: Partial for interim results, Final per finalised segment, SpeechStarted and SpeechEnded from voice activity, Usage from the closing metadataDEEPGRAM_API_KEY
MuseSttmusemuse-voice-transcribe-1.0Meta's realtime WebSocket: Started, cumulative Partials, one Final per turn, SpeechStarted and SpeechEnded, Speaker with diarization, Progress, Usage; a session lasts at most 60 minutesMETA_API_KEY or MODEL_API_KEY
WhisperApiSttsttwhisper-1AudioError::SttOPENAI_API_KEY
AssemblyAiSttsttAn upload and a polled transcription jobAudioError::SttASSEMBLYAI_API_KEY
OnnxSttProviderwhisper-onnx, distil-whisper, moonshineWhisper base by default (On the device)One Final per 30-second segment, numbered from 0None
MlxSttProvidermlxmlx-community/whisper-large-v3-turbo (unquantized safetensors, e.g. *-fp16)AudioError::SttNone; runs on Metal GPU on Apple Silicon (aarch64-apple-darwin), returns AudioError::Stt elsewhere

Each cloud provider has from_env(), which reads the variables above and returns AudioError::Stt naming the missing one. MuseStt::transcribe_stream and its 60-minute limit are described under Muse realtime transcription.

SttOptions is built from SttOptions::default() and its with_* methods; each provider reads the options it supports.

OptionMethodRead by
Language (BCP-47)with_languageGemini (in its prompt), Deepgram, Whisper API, AssemblyAI, Muse, ONNX Whisper and Distil-Whisper (over the config's language), MLX Whisper (multilingual models; .en models ignore it)
Diarizationwith_diarizeDeepgram, AssemblyAI, Muse
Word timestampswith_word_timestampsDeepgram, Whisper API
Smart formattingwith_smart_formatDeepgram
Modelwith_model_hintDeepgram's stream
Domain vocabularywith_keywordsMuse
Likely languageswith_language_biasMuse

Transcribe a recording

use adk_audio::{AudioFormat, GeminiStt, SttOptions, SttProvider, decode};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let audio = decode(&std::fs::read("meeting.wav")?, AudioFormat::Wav)?;

    let stt = GeminiStt::from_env()?;
    let options = SttOptions::default().with_language("en-US");
    let transcript = stt.transcribe(&audio, &options).await?;

    println!("{}", transcript.text);
    Ok(())
}

A Transcript carries text, per-Word timings and confidence, the Speakers found by diarization, an overall confidence and language_detected.

Live transcription

transcribe_stream takes a stream of AudioFrames and returns a TranscriptStream of AudioResult<TranscriptEvent>.

EventMeaning
Started { session_id }The provider accepted the session
SpeechStarted { turn_id, offset_ms }Speech began; later events with the same turn_id belong to it
Partial { turn_id, text }The current hypothesis for the turn, in full: replace the text shown, never append
Final { turn_id, transcript }Text the provider will not revise
SpeechEnded { turn_id, offset_ms }Speech stopped
Speaker { label, offset_ms }The speaker changed (diarization)
Progress { processed_ms }Audio the provider has processed so far
Usage { audio_ms }The audio the session is billed for

TranscriptEvent is #[non_exhaustive], so a match on it keeps a wildcard arm. Dropping the stream stops the provider's work for it: DeepgramStt stops sending and closes its socket, and the caller's audio stream is released.

use adk_audio::{
    AudioFormat, AudioFrame, DeepgramStt, SttOptions, SttProvider, TranscriptEvent, decode,
};
use futures::{StreamExt, stream};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Deepgram's stream takes 16 kHz mono PCM16; 100 ms frames stand in for a microphone.
    let call = decode(&std::fs::read("call-16k-mono.wav")?, AudioFormat::Wav)?;
    let frames: Vec<AudioFrame> =
        call.data.chunks(3_200).map(|chunk| AudioFrame::new(chunk.to_vec(), 16_000, 1)).collect();

    let stt = DeepgramStt::from_env()?;
    let options = SttOptions::default().with_language("en").with_diarize(true);
    let mut events = stt.transcribe_stream(Box::pin(stream::iter(frames)), &options).await?;

    let mut shown = String::new();
    while let Some(event) = events.next().await {
        match event? {
            TranscriptEvent::Partial { text, .. } => shown = text,
            TranscriptEvent::Final { transcript, .. } => {
                println!("{}", transcript.text);
                shown.clear();
            }
            TranscriptEvent::Speaker { label, .. } => println!("[{label}]"),
            TranscriptEvent::Usage { audio_ms } => println!("billed for {audio_ms} ms"),
            _ => {}
        }
    }
    Ok(())
}

Moving from 2.x

In 2.x, transcribe_stream yielded Transcripts, and nothing told an interim result from a final one. In 3.0 it yields TranscriptEvents, has a default implementation that returns AudioError::Stt, and SttOptions is #[non_exhaustive].

2.x3.0
A stream item Ok(transcript) for interim textOk(TranscriptEvent::Partial { text, .. })
A stream item Ok(transcript) for final textOk(TranscriptEvent::Final { transcript, .. })
—Started, SpeechStarted, SpeechEnded, Speaker, Progress, Usage
An implementation returns Pin<Box<dyn Stream<Item = AudioResult<Transcript>> + Send>>It returns TranscriptStream
A provider without streaming implements transcribe_stream to fail or to return an empty streamIt leaves transcribe_stream out; the default returns AudioError::Stt
GeminiStt and WhisperApiStt streams end at once with no itemsThey return AudioError::Stt, which says to call transcribe with the buffered audio
SttOptions { language: Some(..), ..Default::default() }SttOptions::default().with_language(..)

The 2.x → 3.0 migration guide lists the change with the rest of the release.

Write a provider

A provider implements transcribe, and transcribe_stream when it can stream. This one hears the same words in any audio, the way a test double does, and runs without a key:

use std::pin::Pin;

use adk_audio::{
    AudioFrame, AudioResult, SttOptions, SttProvider, Transcript, TranscriptEvent,
    TranscriptStream,
};
use async_trait::async_trait;
use futures::{Stream, StreamExt, stream};

struct ScriptedStt {
    words: String,
}

#[async_trait]
impl SttProvider for ScriptedStt {
    async fn transcribe(&self, _audio: &AudioFrame, _opts: &SttOptions) -> AudioResult<Transcript> {
        Ok(Transcript { text: self.words.clone(), confidence: 1.0, ..Default::default() })
    }

    async fn transcribe_stream(
        &self,
        audio: Pin<Box<dyn Stream<Item = AudioFrame> + Send>>,
        _opts: &SttOptions,
    ) -> AudioResult<TranscriptStream> {
        let words = self.words.clone();
        let heard = audio.fold(0_u64, |ms, frame| async move { ms + u64::from(frame.duration_ms) });
        let events = stream::once(heard).flat_map(move |audio_ms| {
            let first = words.split(' ').next().unwrap_or_default().to_string();
            let transcript = Transcript { text: words.clone(), ..Default::default() };
            stream::iter([
                Ok(TranscriptEvent::Partial { turn_id: Some(0), text: first }),
                Ok(TranscriptEvent::Final { turn_id: Some(0), transcript }),
                Ok(TranscriptEvent::Usage { audio_ms }),
            ])
        });
        Ok(Box::pin(events))
    }
}

/// A provider without streaming: the trait's default `transcribe_stream` refuses.
struct BatchOnly;

#[async_trait]
impl SttProvider for BatchOnly {
    async fn transcribe(&self, _audio: &AudioFrame, _opts: &SttOptions) -> AudioResult<Transcript> {
        Ok(Transcript::default())
    }
}

#[tokio::main]
async fn main() -> AudioResult<()> {
    let stt = ScriptedStt { words: "pay the invoice".into() };
    let audio = || Box::pin(stream::iter(vec![AudioFrame::silence(16_000, 1, 500); 4]));

    let mut events = stt.transcribe_stream(audio(), &SttOptions::default()).await?;
    while let Some(event) = events.next().await {
        println!("{:?}", event?);
    }

    let refused = BatchOnly.transcribe_stream(audio(), &SttOptions::default()).await;
    assert!(refused.is_err());
    Ok(())
}

It prints the Partial with "pay", the Final with "pay the invoice", and Usage { audio_ms: 2000 }.

Text to speech

ProviderFeatureModelVoicessynthesize_streamCredentials
GeminiTtsttsgemini-3.8-flash-tts; with_model sets another30 named voices (Kore, Puck, …); with_speakers voices a dialogue between named speakersOne frameGEMINI_API_KEY or GOOGLE_API_KEY
ElevenLabsTtsttseleven_multilingual_v2Four catalog voices; any ElevenLabs voice idChunks as they arriveELEVENLABS_API_KEY
OpenAiTtsttstts-1; hd() selects tts-1-hdalloy, echo, fable, onyx, nova, shimmerOne frameOPENAI_API_KEY
CartesiaTtsttssonic-3.5Two catalog voices; any Cartesia voice idOne frameCARTESIA_API_KEY
OnnxTtsProvider + KokoroPreprocessorkokoroKokoro-82M from a local model directoryThe voices in Kokoro's .npz voices fileThe finished audio in 100 ms framesNone
ChatterboxTtsProviderchatterboxonnx-community/chatterbox-ONNX; ChatterboxVariant Fp32 (default), Fp16, Q4, Q4F16Cloned from ChatterboxConfig::reference_wav, or the repository's default_voice.wavThe finished audio in 100 ms framesNone
Qwen3TtsNativeProviderqwen3-ttsQwen3TtsVariant::Small (0.6B) or Large (1.7B)vivian, serena, dylan, eric, ryan, aiden, uncle_fu, ono_anna, sohee; 10 languagesThe finished audio in 100 ms framesNone
MlxTtsProvidermlxmlx-community/Kokoro-82M-bf16——None; synthesize returns AudioError::Tts, since MLX TTS inference is not yet implemented

The cloud providers return 24 kHz mono PCM16. Each has from_env() and new(CloudTtsConfig); CloudTtsConfig::with_base_url points one at another endpoint.

use adk_audio::{AudioFormat, GeminiTts, TtsProvider, TtsRequest, encode};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let tts = GeminiTts::from_env()?;
    let request = TtsRequest {
        text: "Your invoice is paid.".into(),
        voice: "Kore".into(),
        ..Default::default()
    };
    let frame = tts.synthesize(&request).await?;

    std::fs::write("paid.wav", encode(&frame, AudioFormat::Wav)?)?;
    println!("{} ms at {} Hz", frame.duration_ms, frame.sample_rate);
    Ok(())
}

TtsRequest also takes language, speed (1.0 by default), pitch and an emotion hint: Neutral, Happy, Sad, Angry, Whisper, Excited or Calm.

On the device

The on-device recognisers and voices need no key, and their audio never leaves the machine.

Recognisers

OnnxSttConfig::builder() picks the recogniser; OnnxSttProvider::new(config, &registry) loads it. Audio of any rate and channel count is downmixed to mono and resampled to 16 kHz.

BackendFeatureVariants and model
SttBackend::Whisper (default)whisper-onnxWhisperModelSize::Tiny, Base (default), Small, Medium, LargeV3Turbo → onnx-community/whisper-<size>
SttBackend::DistilWhisperdistil-whisperDistilWhisperVariant::DistilSmallEn (default), DistilMediumEn, DistilLargeV3 → distil-whisper/distil-small.en, distil-medium.en, distil-large-v3
SttBackend::MoonshinemoonshineMoonshineVariant::Tiny (default), Base → usefulsensors/moonshine-tiny-onnx, moonshine-base-onnx

The builder also sets beam_size (1 to 10, 1 by default), temperature (0.0 by default), language (detected when unset) and execution_provider. OnnxSttProvider::default_whisper() loads Whisper base.

use adk_audio::{
    AudioFormat, LocalModelRegistry, OnnxSttConfig, OnnxSttProvider, SttBackend, SttOptions,
    SttProvider, WhisperModelSize, decode,
};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let config = OnnxSttConfig::builder()
        .stt_backend(SttBackend::Whisper)
        .model_size(WhisperModelSize::Small)
        .language("en")
        .build()?;
    assert_eq!(config.model_id(), "onnx-community/whisper-small");

    let stt = OnnxSttProvider::new(config, &LocalModelRegistry::default()).await?;
    let audio = decode(&std::fs::read("note.wav")?, AudioFormat::Wav)?;
    let transcript = stt.transcribe(&audio, &SttOptions::default()).await?;

    println!("{}", transcript.text);
    Ok(())
}

The example needs the whisper-onnx feature.

MLX Whisper (Apple Silicon)

With the mlx feature (which requires cmake and Xcode's Metal toolchain to build on Apple Silicon), MlxSttProvider runs Whisper locally on Metal GPU via mlx-rs (aarch64-apple-darwin). Audio of any sample rate and channel count is downmixed to mono, resampled to 16 kHz, and decoded greedily in 30-second windows up to MlxSttConfig::max_duration_secs (600 s by default) on a dedicated worker thread so the async runtime never blocks.

  • Checkpoints: unquantized safetensors (weights.safetensors or model.safetensors), including the default mlx-community/whisper-large-v3-turbo and mlx-community/whisper-*-fp16; .npz-only and quantized (-4bit/-8bit) checkpoints return AudioError::Stt.
  • Tokenizer: uses tokenizer.json in the model directory when present, otherwise downloads only tokenizer.json from the matching openai/whisper-* repository based on config.json n_vocab.
  • Language: .en checkpoints (n_vocab < 51865) ignore SttOptions::language; multilingual checkpoints default to "en" when language is None.
  • Silence: a 30-second window whose RMS level is below about -80 dBFS is skipped and yields no text, so audio that is silent throughout returns an empty transcript.
  • Limits: audio longer than max_duration_secs returns AudioError::Stt. The worker reserves buffers for at most 600 s of audio up front; a higher limit grows them with the audio submitted. A request whose caller drops it stops at the next 30-second window.
  • Other platforms and streaming: on non-Apple-Silicon targets, --features mlx compiles (load-only) and transcribe returns AudioError::Stt. transcribe_stream also returns AudioError::Stt.
  • Build requirements on Apple Silicon (--features mlx and --features all): cmake and Xcode's Metal toolchain. The mlx-sys build fetches MLX from GitHub, so it needs network access, and writes mlx.metallib (about 175 MB) under ~/.mlx/lib/.

Voices

VoiceWhat it needs
Kokoro-82M (kokoro)espeak-ng installed (brew install espeak-ng pkg-config; apt-get install espeak-ng libespeak-ng-dev), the model directory on disk, and Kokoro's voices file: KokoroPreprocessor::new(voices_path, "en-us") passed to OnnxTtsProvider::with_preprocessor(config, model_dir, preprocessor), with OnnxModelConfig::onnx_filename naming the model's file
Chatterbox (chatterbox)ChatterboxTtsProvider::load(ChatterboxConfig::default()); set reference_wav to clone a voice and exaggeration (0.0–1.0, 0.5 by default) for expressiveness; it runs on the CPU unless execution_provider says otherwise
Qwen3-TTS (qwen3-tts)Qwen3TtsNativeProvider::new(variant), or from_dir for a model already on disk; on macOS it runs on Metal when the build's candle-core has Metal support and on the CPU otherwise; elsewhere on the CPU. The request's voice is a speaker (vivian), a language (lang:zh) or both (vivian:zh)
Another ONNX modelOnnxTtsProvider::new(OnnxModelConfig, &registry) with the model's Hugging Face id; its tokenizer.json drives TokenizerPreprocessor

Model downloads

ProviderWhere the weights come from
OnnxSttProvider, OnnxTtsProvider::new, Qwen3TtsNativeProvider::new, the MLX providersLocalModelRegistry: a directory <org>--<name> under its cache (~/.cache/adk-audio/models by default; LocalModelRegistry::new(dir) sets another) is used as is; otherwise every file of the Hugging Face repository is downloaded on first use into the Hugging Face cache
ChatterboxTtsProviderThe model, tokenizer and default_voice.wav files from its repository, downloaded on first use into the Hugging Face cache
OnnxTtsProvider::with_preprocessor, Qwen3TtsNativeProvider::from_dirThe directory you pass; nothing is downloaded

The first call that loads a model can therefore download hundreds of megabytes. A download that fails is AudioError::ModelDownload.

Execution providers

OnnxExecutionProvider is Cpu, Cuda, CoreMl or DirectMl; auto_detect() returns CoreMl on macOS and Cpu elsewhere. Cuda runs only with the onnx-cuda feature and CoreMl only with onnx-coreml; without its feature, and for DirectMl, a provider logs a warning and the session runs on the CPU.

Speech as agent tools

TranscribeTool and SpeakTool are adk_core::Tools over any provider, for an agent that hears or speaks.

ToolNameArgumentsReturns
TranscribeTool::new(stt)transcribeaudio_data (base64 PCM16), sample_rate (16000 by default), languagetext, confidence
SpeakTool::new(tts, default_voice)speaktext, voice, emotionduration_ms, sample_rate
use std::sync::Arc;

use adk_audio::{GeminiStt, GeminiTts, SpeakTool, TranscribeTool};
use adk_core::Tool;

fn main() -> adk_audio::AudioResult<()> {
    let tools: Vec<Arc<dyn Tool>> = vec![
        Arc::new(TranscribeTool::new(Arc::new(GeminiStt::from_env()?))),
        Arc::new(SpeakTool::new(Arc::new(GeminiTts::from_env()?), "Kore")),
    ];
    for tool in &tools {
        println!("{}", tool.name());
    }
    Ok(())
}

A cloud provider's billing() names the vendor and model its calls are billed under, and the two tools meter each call against the run: TranscribeTool in audioMillis, SpeakTool in characters. These providers carry no per-unit price, so under a run budget's cost cap or a spend-ledger limit their calls are refused before they are sent; RunBudget::allow_unpriced_models() lets a budget's cost cap admit them. See Calls billed in units. MuseStt returns None from billing(), since the Muse clients meter their own calls at the catalog's price, and so do the local models, which are not metered.

Speech with adk-audio - وثائق ADK-Rust | ADK-Rust