AI Avatar Master of Ceremonies
A stage AI avatar host with gap-free clip switching and live voice takeover.
- Voice AI
- Web products
- Role
- Sole engineer
- Client
- First Gulf Forum on AI in Civil Service, hosted by Qatar's Civil Service Bureau
- Timeline
- Nov 2025 (about 36 hours)
- Status
- Live in production

- commits in about 36 hours
- 21
- commits in about 36 hours
- video clips preloaded, about 200 MB
- 15
- video clips preloaded, about 200 MB
- show segments plus backup takes
- 11 + 2
- show segments plus backup takes
- visemes mapped to mouth sprites
- 15 to 8
- visemes mapped to mouth sprites
- pitch-shift window for live voice
- 30 ms
- pitch-shift window for live voice
The problem
The event needed a lifelike AI presenter, a Qatari host in traditional dress, to run the programme on stage. Running it live means switching between about 15 large clips on a stage display with no black frames or stalls, and looking natural between scripted segments.
Programmes slip. When a speaker runs late or an unscripted announcement comes up, an operator must be able to speak as the avatar, with a modulated voice and a moving mouth. And there has to be a mode that cannot fail in front of an audience.
Architecture
Cue a segment
The operator clicks the next segment. A PLAY_CUSTOM_VIDEO message crosses the BroadcastChannel and the display reveals a clip that is already decoded, then returns to the idle loop when it ends.
- Service
- Data
- AI model
- External
Hard problems I solved
No black frames between clips
Swapping a video element's src forces a reload and decode, which shows a black frame. On a stage screen, every cut between about 15 large clips (up to 30 MB each) would flash.
Approach. Every clip is mounted at once as its own <video preload="auto"> and the active one is chosen with opacity, visibility and z-index. A preloader waits for canplaythrough on every file and shows progress before the show starts, so playback never waits on the network mid-segment.
Hiding the cut between idle and talking
The avatar breathes in an 8 s idle loop and gestures in a 7.6 s talking loop. Switching at an arbitrary point makes the body jump, and the outgoing clip's audio kept playing in the background.
Approach. The target clip is seeked to the same relative phase as the current one and only revealed on its seeked event. The outgoing clip is paused first, and the current-clip ref is updated before the seek so rapid key presses cannot race each other.
Getting live audio from one window to another
The operator's processed voice has to play from the stage window on the stage audio device, but a BroadcastChannel cannot carry a MediaStream.
Approach. A local WebRTC peer connection whose offer, answer and ICE candidates are signalled over the BroadcastChannel. Two bugs from the log: ICE candidates must be serialised with toJSON() before postMessage, and lip-sync has to use Tone's rawContext to avoid an AudioContext mismatch.
Low-latency voice changing
The earlier version captured audio in 0.5 s AudioWorklet chunks (24,000 samples at 48 kHz), so the voice lagged behind the operator by at least half a second.
Approach. Replaced with a streaming Tone.js graph: PitchShift with a 0.03 s window, then reverb, a compressor at -30 dB and 3:1, and gain, all connected to a MediaStreamDestination that feeds WebRTC.
Deciding when the avatar talks
Push-to-talk alone made the avatar move its mouth during the pauses between the operator's words.
Approach. A level detector on the raw mic with hysteresis: talking starts above 15 on the analyser's average spectrum level and stops only after the level stays below 5 for a full second. Any sound in that second cancels the pending stop.
Defaults chosen for a live audience
A long show with repeated push-to-talk sessions leaks audio resources, and every optional feature is one more thing that can fail on stage.
Approach. Every spacebar release disposes the Tone nodes, stops the mic tracks, closes the AudioContext and closes the peer connection. The last commits before the event made video-only Simple Mode and lip-sync-off the defaults, and added backup takes of the opening and part 1.
Code
The operator's voice is processed in a streaming graph, not in chunks, and leaves through WebRTC because BroadcastChannel cannot carry media. Candidates are serialised first to avoid a clone error.
micInputRef.current = new Tone.UserMedia();
await micInputRef.current.open();
pitchShiftRef.current = new Tone.PitchShift({
pitch: pitchShift,
windowSize: 0.03, // Smaller window for less latency
wet: 1
});
reverbRef.current = new Tone.Reverb({ decay: 1.5, wet: reverbAmount * 0.3 });
await reverbRef.current.generate();
compressorRef.current = new Tone.Compressor(-30, 3);
gainRef.current = new Tone.Gain(volume);
// Mic -> PitchShift -> Reverb -> Compressor -> Gain -> Destination
micInputRef.current.connect(pitchShiftRef.current);
pitchShiftRef.current.connect(reverbRef.current);
reverbRef.current.connect(compressorRef.current);
compressorRef.current.connect(gainRef.current);
const destination = Tone.getContext().createMediaStreamDestination();
gainRef.current.connect(destination as any);
await setupWebRTC(destination.stream);
// inside setupWebRTC: serialize the candidate to avoid clone errors
peerConnectionRef.current.onicecandidate = (event) => {
if (event.candidate && broadcastRef.current)
broadcastRef.current.postMessage({ type: 'WEBRTC_ICE_CANDIDATE', candidate: event.candidate.toJSON() });
};const dataArray = new Uint8Array(analyserRef.current.frequencyBinCount);
analyserRef.current.getByteFrequencyData(dataArray);
const average = dataArray.reduce((a, b) => a + b) / dataArray.length;
const TALKING_THRESHOLD = 15; // switch to talking video
const SILENCE_THRESHOLD = 5; // switch back to idle
const SILENCE_DELAY = 1000; // 1 second delay before switching to idle
if (average > TALKING_THRESHOLD) {
if (!isCurrentlyTalking.current) {
isCurrentlyTalking.current = true;
broadcastRef.current.postMessage({ type: 'LIP_SYNC_START', lipSyncEnabled });
}
if (silenceTimeoutRef.current) { // any sound cancels a pending stop
clearTimeout(silenceTimeoutRef.current);
silenceTimeoutRef.current = null;
}
} else if (average < SILENCE_THRESHOLD && isCurrentlyTalking.current && !silenceTimeoutRef.current) {
silenceTimeoutRef.current = window.setTimeout(() => {
isCurrentlyTalking.current = false;
broadcastRef.current?.postMessage({ type: 'LIP_SYNC_STOP' });
silenceTimeoutRef.current = null;
}, SILENCE_DELAY);
}
requestAnimationFrame(monitorAudioLevel);const findMatchingFrame = (sourceVideo: HTMLVideoElement, targetVideo: HTMLVideoElement): number => {
const relativePosition = (sourceVideo.currentTime % sourceVideo.duration) / sourceVideo.duration;
return relativePosition * targetVideo.duration;
};
const switchToVideo = (newVideo: VideoName) => { // union of clip names, abridged
if (newVideo === currentVideoRef.current) return; // Check ref for immediate state
const currentVid = videoRefs.current[currentVideoRef.current];
const newVid = videoRefs.current[newVideo];
if (currentVid) currentVid.pause(); // PAUSE the current video to stop its audio
currentVideoRef.current = newVideo; // Update ref IMMEDIATELY so rapid calls don't conflict
if (currentVid && newVid && currentVid.duration && newVid.duration) {
const onSeeked = () => {
newVid.removeEventListener('seeked', onSeeked);
newVid.play().catch(err => console.error('Play error:', err));
setCurrentVideo(newVideo); // reveal only once the frame is ready
};
newVid.addEventListener('seeked', onSeeked);
newVid.currentTime = findMatchingFrame(currentVid, newVid);
}
...
};What I built
Show control
- Operator console and fullscreen stage display as two windows of one React app
- BroadcastChannel message bus for cues, idle and talking states, and signalling
- Ordered segment buttons from entrance to exit, with backup takes of the opening and part 1
- Segment text shown on hover so the operator can follow along
Playback
- Every clip mounted at once and switched by opacity, visibility and z-index
- Preloader with a progress bar that waits for canplaythrough on every clip
- Idle to talking switch seeked to the same phase and revealed on seeked
- Automatic return to the idle loop when a segment ends
Live voice
- Spacebar push-to-talk, with video-only Simple Mode as the show default
- Full Mode: Tone.js pitch shift, reverb, compressor and gain on the operator's mic
- Processed track streamed to the stage window over a local WebRTC connection
- Level detector with hysteresis that decides when the avatar is talking
Lip-sync (optional)
- wawa-lipsync visemes mapped onto 8 mouth sprites
- MediaPipe Face Mesh at 20 fps locates the mouth on the playing clip
- Exponential smoothing (0.15 talking, 0.20 idle), with precomputed tracking JSON as fallback
Screens
The operator console: every show segment in running order, backup takes and a return-to-idle control.
The avatar running full-size on the portrait LED wall at the forum venue.
The avatar the show was built around: idle and talking loops, scripted segments and live voice takeover.
Full Mode voice controls feeding the Tone.js chain (pitch shift, reverb, compressor, gain) that streams to the stage window.
The 8 mouth sprites. wawa-lipsync's 15 visemes map onto them, and a canvas overlay cross-fades between them over the avatar's mouth.
Stack
Frontend
- React 19.1
- TypeScript 5.9
- Vite 7.1
- Tailwind CSS
Real-time audio
- Tone.js 15.1
- Web Audio AnalyserNode
- WebRTC
- BroadcastChannel
Lip-sync
- wawa-lipsync
- MediaPipe Face Mesh
- Canvas 2D
Hosting
- Vercel (static)
How it was built
Built solo in about 36 hours before the forum: 21 commits, one author. Earlier face-swap and face-warp experiments (V1 to V5) happened outside this repo, and the avatar clips and mouth sprites were generated offline; this code is the show-control and real-time audio layer around them.
The event script and the officials it names are not published, and the live console is not linked because it shows that script.