By the Outspoken Team · March 21, 2026
Custom Wake Word Detection in React Native
Wake word detection lets your app respond to a spoken phrase without any button press. The user lifts their hands, picks up a tool, or simply walks into a room -- and your app is already listening. On a phone, the use cases range from accessibility tools that need voice activation to smart home remotes, voice-driven fitness apps, and anything else where reaching for the screen is inconvenient.
The standard approach is to send audio to a cloud API. That means network latency, a dependency on connectivity, and sending a continuous audio stream to a third-party server -- none of which is acceptable for a feature that needs to feel instant and private. On-device inference solves all three: it runs locally, works offline, and the audio never leaves the device.
This guide walks through running a full wake word detection pipeline in a React Native app using onnxruntime-react-native and the Expo Audio API. By the end you'll have a working TypeScript implementation that detects a custom wake word in real time.
How the Pipeline Works
Wake word detection doesn't run directly on raw audio. The model trained by Outspoken expects pre-processed audio features, which means you need to run three ONNX models in sequence:
-
melspectrogram.onnx-- Converts raw 16kHz float32 audio into a mel spectrogram. This is a compact frequency-over-time representation that captures what matters acoustically while discarding irrelevant variation. -
embedding_model.onnx-- Converts a window of 76 mel spectrogram frames into a dense embedding vector. This model is shared across all wake words -- it's a general-purpose audio feature extractor trained on a large corpus. -
your_wake_word.onnx-- Your custom model. Takes the last 16 embeddings as input and outputs an activation score between 0 and 1. A score above a threshold (typically 0.5) means the wake word was detected.
You need all three models. The first two are provided by openWakeWord and don't change between wake words -- only the third model is specific to your phrase.
The models are not simply chained once per frame. Each 1280-sample frame produces 5 mel frames, the embedding model needs a window of 76 of them, and your model needs a history of the last 16 embeddings. The pipeline code below keeps that history for you, which is why frames must reach it in order.
Audio requirements:
- 16kHz sample rate
- float32 samples normalized to the range [-1, 1]
- 1280 samples per chunk (approximately 80ms of audio)
Setup
Install Dependencies
npm install onnxruntime-react-nativeExpo only: install expo-audio, which streams the microphone as raw PCM:
npx expo install expo-audioexpo-av is deprecated
Older guides use expo-av for recording. Expo has replaced it with expo-audio (and expo-video), so new projects should use expo-audio. It also has something expo-av lacked: a live PCM stream (useAudioStream), which is what wake word detection needs. Check the expo-audio docs for the SDK version that includes it.
React Native only (a React Native CLI app, without Expo): use react-native-live-audio-stream, which delivers the microphone as PCM chunks, plus buffer to decode them:
npm install react-native-live-audio-stream buffer
cd ios && pod installExpo: you need a development build, not Expo Go
onnxruntime-react-native contains native code, so it cannot run in Expo Go. After installing it, run npx expo prebuild --clean and then npx expo run:ios or npx expo run:android (or make an EAS development build). Without this, the app crashes with Cannot read property 'install' of null.
The inference code in this guide is the same either way -- only the microphone setup differs. Each section below says whether it is for Expo, for React Native, or for both.
Check for latest versions
Package APIs evolve quickly. Always check the onnxruntime-react-native npm page for the latest release before installing. As of early 2026, version 1.20.x is current.
Permissions
Expo only -- the expo-audio config plugin adds the native microphone permissions for you. Add it to app.json and rebuild your development build:
{
"expo": {
"plugins": [
[
"expo-audio",
{ "microphonePermission": "This app uses the microphone to detect the wake word." }
]
]
}
}React Native only (without Expo) -- add the permissions by hand.
Android, android/app/src/main/AndroidManifest.xml:
<uses-permission android:name="android.permission.RECORD_AUDIO" />iOS, ios/YourApp/Info.plist:
<key>NSMicrophoneUsageDescription</key>
<string>This app uses the microphone to detect the wake word.</string>At runtime, request the permission before you start the stream.
Expo only:
import { requestRecordingPermissionsAsync } from "expo-audio";
const { granted } = await requestRecordingPermissionsAsync();
if (!granted) {
throw new Error("Microphone permission not granted");
}React Native only: iOS asks automatically when the stream starts. On Android, request it yourself:
import { PermissionsAndroid, Platform } from "react-native";
if (Platform.OS === "android") {
const result = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.RECORD_AUDIO);
if (result !== PermissionsAndroid.RESULTS.GRANTED) {
throw new Error("Microphone permission not granted");
}
}Bundle the ONNX Models
You need to ship three .onnx files with your app: melspectrogram.onnx, embedding_model.onnx, and your custom wake word model downloaded from the Outspoken dashboard.
The melspectrogram.onnx and embedding_model.onnx files are available in the openWakeWord GitHub repository.
You can download the two shared files straight into your project from the Outspoken site:
mkdir -p assets/models
curl -L -o assets/models/melspectrogram.onnx https://outspoken.cloud/models/melspectrogram.onnx
curl -L -o assets/models/embedding_model.onnx https://outspoken.cloud/models/embedding_model.onnxPlace all three files in your project's assets/models/ directory (both Expo and React Native), then configure Metro to treat .onnx files as assets.
Expo only:
// metro.config.js
const { getDefaultConfig } = require("expo/metro-config");
const config = getDefaultConfig(__dirname);
config.resolver.assetExts.push("onnx");
module.exports = config;React Native only (without Expo):
// metro.config.js
const { getDefaultConfig, mergeConfig } = require("@react-native/metro-config");
const defaults = getDefaultConfig(__dirname);
module.exports = mergeConfig(defaults, {
resolver: { assetExts: [...defaults.resolver.assetExts, "onnx"] },
});After adding the files or changing the config, do a clean build so Metro and the native project pick them up. Expo only: npx expo start --clear, and if you also installed packages with native code, npx expo prebuild --clean followed by npx expo run:ios or npx expo run:android. React Native only: npx react-native start --reset-cache, then rebuild the app.
Then reference the files with require():
const MELSPECTROGRAM_MODEL = require("../assets/models/melspectrogram.onnx");
const EMBEDDING_MODEL = require("../assets/models/embedding_model.onnx");
const WAKE_WORD_MODEL = require("../assets/models/hey_jarvis.onnx");Model file sizes
The melspectrogram and embedding models are shared infrastructure -- about 1.1 MB and 1.3 MB. Your custom wake word model is around 0.9 MB at the default layer size of 96, and about 3.7 MB at 128. See the training guide for details on how layer size affects model size and accuracy.
Implementation
Loading the ONNX Sessions
Load all three models once when the component mounts. ONNX Runtime sessions are expensive to initialize, so hold them in a ref and reuse them across audio chunks.
import { InferenceSession } from "onnxruntime-react-native";
import { useRef, useEffect } from "react";
interface WakeWordSessions {
melspectrogram: InferenceSession;
embedding: InferenceSession;
wakeWord: InferenceSession;
}
function useWakeWordSessions(): React.MutableRefObject<WakeWordSessions | null> {
const sessions = useRef<WakeWordSessions | null>(null);
useEffect(() => {
let cancelled = false;
async function load() {
const [melspectrogram, embedding, wakeWord] = await Promise.all([
InferenceSession.create(MELSPECTROGRAM_MODEL),
InferenceSession.create(EMBEDDING_MODEL),
InferenceSession.create(WAKE_WORD_MODEL),
]);
if (!cancelled) {
sessions.current = { melspectrogram, embedding, wakeWord };
}
}
load().catch(console.error);
return () => {
cancelled = true;
};
}, []);
return sessions;
}Streaming the Microphone at 16kHz
Expo only. useAudioStream from expo-audio captures raw PCM from the microphone in real time and hands it to you in a callback. There are no files to write or re-read.
import { useAudioStream } from "expo-audio";
const { stream, isStreaming } = useAudioStream({
sampleRate: 16000, // what the models expect
channels: 1, // mono
encoding: "float32", // samples are already in [-1, 1], so no conversion is needed
onBuffer: (buffer) => {
// buffer.data is an ArrayBuffer of float32 samples
// buffer.sampleRate is the rate you actually got
},
});
await stream.start(); // after the microphone permission is granted
stream.stop(); // when you are doneSample rate is a request, not a guarantee
The sample rate you ask for may differ if the hardware cannot deliver it. Check buffer.sampleRate on the first buffer. If it is not 16000, downsample before running inference (for 48kHz, keeping every third sample after a simple low-pass is good enough for wake word work).
React Native only (without Expo). react-native-live-audio-stream emits base64-encoded 16-bit PCM chunks. Convert them to float32 in the range [-1, 1] before they go into the models:
import LiveAudioStream from "react-native-live-audio-stream";
import { Buffer } from "buffer";
LiveAudioStream.init({
sampleRate: 16000, // what the models expect
channels: 1, // mono
bitsPerSample: 16,
audioSource: 6, // Android: voice recognition
bufferSize: 2560,
});
LiveAudioStream.on("data", (base64: string) => {
const bytes = Buffer.from(base64, "base64");
const pcm = new Int16Array(bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.length));
const samples = Float32Array.from(pcm, (v) => v / 32768);
// samples is a Float32Array of 16kHz mono audio, ready for the frame cutter below
});
LiveAudioStream.start(); // after microphone permission is granted
LiveAudioStream.stop(); // when you are doneCutting the Stream into Frames
This part is the same for Expo and React Native. Buffers arrive in whatever size the platform chooses, but the models expect frames of exactly 1280 samples (80 ms). Collect the samples and cut a frame whenever you have enough:
const FRAME_SIZE = 1280;
/** Collects incoming samples and returns every complete 1280-sample frame. */
function createFrameCutter(frameSize = FRAME_SIZE) {
let pending = new Float32Array(0);
return (incoming: Float32Array): Float32Array[] => {
const all = new Float32Array(pending.length + incoming.length);
all.set(pending);
all.set(incoming, pending.length);
const frames: Float32Array[] = [];
let i = 0;
for (; i + frameSize <= all.length; i += frameSize) {
frames.push(all.slice(i, i + frameSize));
}
pending = all.slice(i); // keep the remainder for the next buffer
return frames;
};
}Running the Three-Model Pipeline
createPipeline wraps the three sessions and keeps the rolling history between calls. Give it every 1280-sample frame, in order, and it returns the latest wake word score:
import { InferenceSession, Tensor } from "onnxruntime-react-native";
export function createPipeline(sessions: WakeWordSessions) {
let melFrames: Float32Array[] = []; // 32 values per frame
const embeddings = Array.from({ length: 16 }, () => new Float32Array(96)); // the last 16 embeddings
// ONNX Runtime reuses its output buffers, so copy whatever you keep.
async function run(session: InferenceSession, data: Float32Array, dims: number[]) {
const out = await session.run({ [session.inputNames[0]]: new Tensor("float32", data, dims) });
return Float32Array.from(out[session.outputNames[0]].data as Float32Array);
}
return async function runInference(frame: Float32Array): Promise<number> {
// 1. 1280 audio samples -> 5 mel frames, rescaled the way the embedding model expects
const mel = await run(sessions.melspectrogram, frame, [1, 1280]);
for (let i = 0; i < 5; i++) {
melFrames.push(mel.slice(i * 32, (i + 1) * 32).map((v) => v / 10 + 2));
}
let score = 0;
// 2. every 76 mel frames -> one embedding, then slide the window by 8 frames
while (melFrames.length >= 76) {
const window = new Float32Array(76 * 32);
melFrames.slice(0, 76).forEach((f, i) => window.set(f, i * 32));
embeddings.shift();
embeddings.push(await run(sessions.embedding, window, [1, 76, 32, 1]));
melFrames = melFrames.slice(8);
// 3. the last 16 embeddings -> wake word score (0 to 1)
const history = new Float32Array(16 * 96);
embeddings.forEach((e, i) => history.set(e, i * 96));
score = (await run(sessions.wakeWord, history, [1, 16, 96]))[0];
}
return score;
};
}Why the rescale and the windows matter
The v / 10 + 2 rescale of the mel output and the window sizes (76 mel frames, 16 embeddings) are what the models were trained with. If you skip them the model still runs, but it never fires. The code reads the tensor names from each session (inputNames[0], outputNames[0]) instead of hard-coding them, so it works with any model export.
Threshold-Based Activation Detection
Wrap the pipeline in a detector that queues frames, runs them one at a time and compares the score to a threshold. Scores above the threshold trigger the wake word callback.
const ACTIVATION_THRESHOLD = 0.5;
// Debounce: minimum ms between activations to avoid repeated triggers
const DEBOUNCE_MS = 2000;
// If inference falls behind, drop the oldest frames instead of building a backlog
const MAX_QUEUED_FRAMES = 4;
interface WakeWordDetectorOptions {
threshold?: number;
onActivation: () => void;
}
function useWakeWordDetector({ threshold = ACTIVATION_THRESHOLD, onActivation }: WakeWordDetectorOptions) {
const sessions = useWakeWordSessions();
const pipelineRef = useRef<ReturnType<typeof createPipeline> | null>(null);
const lastActivationRef = useRef<number>(0);
const queueRef = useRef<Float32Array[]>([]);
const drainingRef = useRef(false);
const drain = async () => {
if (drainingRef.current || !sessions.current) return;
if (!pipelineRef.current) pipelineRef.current = createPipeline(sessions.current);
drainingRef.current = true;
try {
for (let frame = queueRef.current.shift(); frame; frame = queueRef.current.shift()) {
const score = await pipelineRef.current(frame);
if (score >= threshold) {
const now = Date.now();
if (now - lastActivationRef.current > DEBOUNCE_MS) {
lastActivationRef.current = now;
onActivation();
}
}
}
} catch (err) {
console.error("Wake word inference error:", err);
} finally {
drainingRef.current = false;
}
};
// The pipeline keeps a rolling history, so frames must be processed in order.
// Queue them instead of dropping a frame while another is still running.
const processChunk = (audioChunk: Float32Array) => {
queueRef.current.push(audioChunk);
while (queueRef.current.length > MAX_QUEUED_FRAMES) queueRef.current.shift();
void drain();
};
return { processChunk, sessionsReady: sessions.current !== null };
}Putting It Together
Expo only. Here is a minimal but complete component that streams the microphone and runs wake word detection on every frame:
import React, { useCallback, useEffect, useRef, useState } from "react";
import { View, Text, Button } from "react-native";
import { requestRecordingPermissionsAsync, useAudioStream } from "expo-audio";
export function WakeWordListener() {
const [activated, setActivated] = useState(false);
const cutFrames = useRef(createFrameCutter()).current;
const { processChunk, sessionsReady } = useWakeWordDetector({
threshold: 0.5,
onActivation: useCallback(() => {
setActivated(true);
setTimeout(() => setActivated(false), 2000);
}, []),
});
const { stream, isStreaming } = useAudioStream({
sampleRate: 16000,
channels: 1,
encoding: "float32",
onBuffer: (buffer) => {
for (const frame of cutFrames(new Float32Array(buffer.data))) {
// processChunk queues frames and processes them in order
processChunk(frame);
}
},
});
const startListening = useCallback(async () => {
const { granted } = await requestRecordingPermissionsAsync();
if (granted && sessionsReady) await stream.start();
}, [stream, sessionsReady]);
useEffect(() => {
return () => stream.stop();
}, [stream]);
return (
<View>
<Button
title={isStreaming ? "Stop" : "Start Listening"}
onPress={isStreaming ? () => stream.stop() : startListening}
disabled={!sessionsReady}
/>
{activated && <Text>Wake word detected!</Text>}
</View>
);
}React Native only (without Expo). Use the same detector and frame cutter, and feed them from react-native-live-audio-stream instead of useAudioStream:
useEffect(() => {
LiveAudioStream.init({ sampleRate: 16000, channels: 1, bitsPerSample: 16, audioSource: 6, bufferSize: 2560 });
LiveAudioStream.on("data", (base64: string) => {
const bytes = Buffer.from(base64, "base64");
const pcm = new Int16Array(bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.length));
for (const frame of cutFrames(Float32Array.from(pcm, (v) => v / 32768))) {
processChunk(frame);
}
});
return () => LiveAudioStream.stop();
}, [processChunk]);Call LiveAudioStream.start() from your button handler once the microphone permission is granted.
Keep inference fast
The stream delivers audio continuously, so processChunk queues frames and works through them in order. If inference falls behind (slower phones), it drops the oldest frames. If that happens a lot, run inference off the main thread and consider a voice-activity gate in front of the model, as described below.
Troubleshooting
Common errors
Select the error you see to find the fix.
TypeError: Cannot read property 'install' of null
The native part of onnxruntime-react-native is not in your app. This happens in Expo Go, or in a development build made before you installed the package.
Expo only: rebuild the native app, then open that build (not Expo Go): npx expo prebuild --clean, then npx expo run:ios or npx expo run:android (or make a new EAS development build). Start Metro with npx expo start --clear.
React Native only: run cd ios && pod install, then rebuild the app.
Unable to resolve module ./assets/models/melspectrogram.onnx
Metro could not find the file.
First, do a clean build. After you add the .onnx files or change metro.config.js, Metro and the native build still have the old file list, and this fixes it most of the time. Expo only: run npx expo start --clear. If you also installed packages with native code, rebuild the native project: npx expo prebuild --clean, then npx expo run:ios or npx expo run:android (or make a new EAS development build). React Native only: run npx react-native start --reset-cache and rebuild the app (on iOS run cd ios && pod install first).
If the error persists, check these in order:
1. The folder. The files must be in assets/models/. Run the command below and check that all three are there.
2. The path. A require path is relative to the file it is written in. Count the folders between the file and the project root: from src/sessions.ts it is ../assets/models/..., from src/hooks/wake-word/sessions.ts it is ../../../assets/models/....
3. The Metro config. .onnx must be listed in assetExts in metro.config.js (see the Metro step), then do the clean build again.
4. The spelling. The name in the error is exactly what Metro looked for. The shared files are called melspectrogram.onnx and embedding_model.onnx.
input 'input_1' is missing in 'feeds'
You are passing a tensor name that the model does not have. The three models use different input names (for example input, input_1 and embeddings), so don't hard-code them. Read the name from the session instead, as the pipeline code does: session.inputNames[0] for the input and session.outputNames[0] for the output.
ReferenceError: Property 'Buffer' doesn't exist
React Native only. The stream code decodes base64 audio with Buffer, which React Native doesn't provide. Install the package and import it at the top of the file.
This app has crashed because it attempted to access privacy-sensitive data without a usage description
iOS. The microphone usage description is missing from the native project. Expo only: add the expo-audio plugin with a microphonePermission text to app.json, then rebuild your development build. React Native only: add NSMicrophoneUsageDescription to ios/YourApp/Info.plist and rebuild. Changes to native permissions need a new build, a reload is not enough.
Native module errors, or a crash in Expo Go
Expo only. onnxruntime-react-native contains native code, which Expo Go does not include. Use a development build instead: npx expo run:ios, npx expo run:android, or an EAS development build. Rebuild after you install any package with native code.
The wake word never triggers
Log the score from the pipeline and see whether it moves when you say the phrase (it should rise well above 0.1). Then check:
1. The sample rate. The audio must be 16 kHz mono. Check buffer.sampleRate (Expo) and downsample if it is not 16000.
2. The permission. The microphone permission must be granted and the stream must be running (isStreaming).
3. The pipeline. Use the pipeline code from this guide as it is: the v / 10 + 2 rescale and the 76-frame and 16-embedding windows are required, and frames must arrive in order.
4. The threshold. Try 0.3 while testing. Your dashboard shows the recommended threshold for your model.
5. The phrase. Say it the way you trained it, at normal volume, close to the microphone.
Still stuck, or want us to build the integration for you? We also do consultancy work. Contact us.
Performance Considerations
Run Inference Off the Main Thread
ONNX Runtime's React Native binding runs inference synchronously on the JS thread by default. For wake word detection, where you're calling inference every 80-200ms, this can cause dropped frames in your UI.
Move the inference loop to a web worker equivalent using React Native's MessageChannel or a library like react-native-worker-threads if your threading requirements are strict. Alternatively, batch inference calls and schedule them with InteractionManager.runAfterInteractions to avoid blocking user interactions.
For most use cases, running inference at 5 Hz (every 200ms) produces acceptable latency without significant UI impact. The three models together take 5-20ms on a modern phone, leaving ample headroom.
Battery Impact
Continuous microphone recording and inference will drain the battery faster than a passive app. Practical mitigation strategies:
- Voice activity detection (VAD) as a gate. Run a lightweight energy threshold check before running the full pipeline. If the RMS amplitude of the chunk is below a floor (e.g., silence or near-silence), skip inference entirely.
- Pause detection while the screen is off. Register an
AppStatelistener and stop recording when the app is backgrounded, if your use case permits. - Reduce chunk overlap. Processing every 1280-sample chunk sequentially gives 80ms resolution. You can process every other chunk (160ms resolution) and most wake words will still be detected reliably.
In informal testing, continuous inference at 5 Hz increases battery drain by roughly 5-10% compared to a passive app on a mid-range Android device. Your mileage will vary.
Model Size on Disk
| Layer Size | Model File Size (measured) |
|---|---|
| 96 (default) | ~0.9 MB |
| 128 | ~3.7 MB |
The shared melspectrogram.onnx (~1.1 MB) and embedding_model.onnx (~1.3 MB) add about 2.4 MB. With the default layer size, the full pipeline takes roughly 3.3 MB on disk, which is small for a mobile app.
Getting Your Custom Model
Train a custom wake word model at Outspoken. Enter your wake word, configure the training parameters, and a GPU worker will produce a trained ONNX model in about 45 minutes. Download it from your dashboard and drop it into assets/models/.
If you want to test a model before integrating it into your app, use the Playground -- it runs the same three-model pipeline in your browser using your microphone, so you can validate detection accuracy without writing any code.
For guidance on choosing training parameters and picking a phonetically strong wake word, see the training guide.
Credits never expire
Training uses one-time model credit packs, and you can test any model in the playground first. You can download standard ONNX/TFLite files for personal, hobby, and prototype use; commercial venue, fleet, resale, or customer deployments require a deployment license.
FAQ
Does wake word detection work offline in a React Native app? Yes. The entire pipeline runs on-device with ONNX Runtime — no network calls, no cloud dependency, and no audio ever leaves the phone.
How much battery does continuous wake word detection use? In informal testing, continuous inference at 5 Hz increased battery drain by roughly 5-10% compared to a passive app on a mid-range Android device. A voice-activity-detection gate before running the full pipeline reduces this further.
Can I use custom wake word detection in a React Native app without Expo?
Yes. The ONNX inference code is identical; only the audio recording layer changes. Use react-native-live-audio-stream (or a similar native module) instead of expo-audio to capture the microphone stream.
Deploying to other platforms? See the Home Assistant integration guide for a turnkey voice assistant setup, or the Raspberry Pi guide for always-on detection on low-power hardware.
Ready to add wake word detection to your app? Create an account and train your first model.