Implementation:23blocks OS Ai maestro Use Speech Level Hook
| Knowledge Sources | |
|---|---|
| Domains | UI, Audio, Animation |
| Last Updated | 2026-10-26 18:00 GMT |
Overview
Concrete tool for sampling speech energy imperatively (not React state) to drive avatar mouth animation at 60fps, via Web Audio AnalyserNode with a synthetic fallback, provided by AI Maestro's `hooks/useSpeechLevel.ts`.
Description
The useSpeechLevel hook exposes speech energy as a `SpeechLevelReader` (a `read()` function and a `mode()` function), deliberately NOT React state — the value is read 60 times per second from a `requestAnimationFrame` loop, and putting it in state would re-render the tree on every frame. It wires a Web Audio `AnalyserNode` to the audio element returned by the TTS provider; for providers that render to an `<audio>` element (OpenAI, ElevenLabs) it reads real waveform RMS; for `web-speech` (which exposes no stream) it falls back to `syntheticLevel`. `createMediaElementSource` is called once per element (guarded by a WeakSet) and re-connects to `destination` (forgetting this silences the audio). The AudioContext resumes on first user gesture.
Usage
Call with `isSpeaking` and a `getAudioElement` callback. Read `level` from the returned `reader.read()` inside a rAF loop, not in render.
Code Reference
Source Location
- Repository: ai-maestro
- File: hooks/useSpeechLevel.ts
- Lines: L1-L132
Signature
export interface SpeechLevelReader {
read: () => number // 0..1 speech energy
mode: () => SpeechLevelMode // 'analyser' | 'synthetic' | 'silent'
}
export function useSpeechLevel({
isSpeaking: boolean
getAudioElement?: () => HTMLAudioElement | null
}): SpeechLevelReader
Import
import { useSpeechLevel, type SpeechLevelReader } from '@/hooks/useSpeechLevel'
I/O Contract
| Name | Type | Description |
|---|---|---|
| reader.read() | number | 0..1 speech energy (call from rAF) |
| reader.mode() | SpeechLevelMode | Source: 'analyser', 'synthetic', 'silent' |
Usage Examples
import { useSpeechLevel } from '@/hooks/useSpeechLevel'
function FaceRig({ isSpeaking, getAudioElement }) {
const reader = useSpeechLevel({ isSpeaking, getAudioElement })
function loop() {
const level = reader.read()
// Drive mouth open with level
requestAnimationFrame(loop)
}
requestAnimationFrame(loop)
}