Lab 30: Interacting with a Custom Voice Client Challenge
Goalโ
In this lab, you will run an ADK voice agent powered by gemini-3.8-live on ADK's headless API server (uv run adk api_server) and build a standalone HTML/JavaScript push-to-talk voice client connected to the /run_live WebSocket endpoint.
Step 1: Prepare the Streaming Agent (streaming_agent)โ
Environment setup:
- 1-Click Launch (Browser): Open in GitHub CodespacesOpen in Google Cloud Shell
- Local machine: If you're continuing the course in sequence,
cdinto theadk-trainingproject you created in Module 2 and skip the block below -- your environment and dependencies already carry forward. If you're starting fresh at this module, create that project first:uv init adk-training --python 3.10 && cd adk-training
uv add "google-adk>=2.1.0" python-dotenv- DevContainer / Codespaces (Alternative): If you opened this repository in a DevContainer or GitHub Codespaces, Python 3.11,
uv,gcloud, and all core ADK dependencies are pre-installed in your container environment.
-
Navigate to your
adk-trainingworkspace directory and create a config-based agent:cd /path/to/your/adk-training
uv run adk create --type=config streaming_agent -
Configure
streaming_agent/root_agent.yamlandstreaming_agent/.env:- Verify
streaming_agent/.envcontains your credentials (eitherGOOGLE_API_KEYfor Google AI Studio, orGOOGLE_GENAI_USE_ENTERPRISE=1,GOOGLE_CLOUD_PROJECT, andGOOGLE_CLOUD_LOCATIONfor Vertex AI). - Replace the contents of
streaming_agent/root_agent.yamlwith:name: streaming_conversational_agent
model: gemini-3.8-live
instruction: |
You are a friendly and talkative assistant. Keep your answers concise. - Important:
/run_liverequires a Gemini Live API model such asgemini-3.8-liveโ standard non-live models likegemini-3.8-flashdo not support bidirectional/run_livestreaming and will close the WebSocket with an error.
- Verify
Step 2: Add the Provided Audio Worklet (streaming_client/audio-processor.js)โ
Create a separate streaming_client/ folder inside adk-training/ so python3 -m http.server never exposes streaming_agent/.env:
cd /path/to/your/adk-training
mkdir -p streaming_client
Inside streaming_client/, create audio-processor.js to resample browser microphone audio down to the 16kHz raw PCM format expected by gemini-3.8-live:
// streaming_client/audio-processor.js (provided)
class AudioProcessor extends AudioWorkletProcessor {
constructor() {
super();
this.targetSampleRate = 16000; // Live API expects 16 kHz PCM input
this.originalSampleRate = sampleRate; // Browser's hardware sample rate
this.resampleRatio = this.originalSampleRate / this.targetSampleRate;
}
process(inputs, outputs, parameters) {
const input = inputs[0];
if (input.length > 0) {
let audioData = input[0]; // First mono channel
if (this.resampleRatio !== 1) {
audioData = this.resample(audioData);
}
this.port.postMessage(audioData);
}
return true; // Keep processor alive
}
resample(audioData) {
const newLength = Math.round(audioData.length / this.resampleRatio);
const resampled = new Float32Array(newLength);
const lastIndex = audioData.length - 1;
for (let i = 0; i < newLength; i++) {
const srcPos = i * this.resampleRatio;
const srcIndex = Math.floor(srcPos);
const nextIndex = Math.min(srcIndex + 1, lastIndex);
const frac = srcPos - srcIndex;
resampled[i] =
audioData[srcIndex] * (1 - frac) + audioData[nextIndex] * frac;
}
return resampled;
}
}
registerProcessor('audio-processor', AudioProcessor);
Step 3: Create the Custom HTML/JavaScript Voice Client (streaming_client/index.html)โ
Exercise: Create streaming_client/index.html using the skeleton below and complete the five // TODO sections.
Notice how the starter architecture avoids two classic browser audio bugs:
- Autoplay Policy Unlock:
playbackAudioContextis created andawait playbackAudioContext.resume()is called right insidestartRecording()(triggered by the user'smousedowngesture), ensuring Chrome/Safari never mute incoming agent audio. - Deterministic Readiness (No
setTimeoutRace): Instead of guessing withsetTimeout(..., 500),connect()awaits session creation, awaitsmicAudioContext.audioWorklet.addModule('audio-processor.js'), and awaits aPromisethat resolves on the WebSocketopenevent before microphone streaming starts.
<!-- streaming_client/index.html (Starter Code) -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ADK Custom Streaming Client</title>
<style>
body { font-family: sans-serif; display: flex; flex-direction: column; align-items: center; }
#status { margin: 10px; padding: 10px; border: 1px solid #ccc; }
#transcript { width: 500px; height: 300px; border: 1px solid #ccc; padding: 10px; overflow-y: scroll; background-color: #f9f9f9; }
p { margin: 5px 0; }
button { margin: 10px; padding: 10px 18px; font-size: 16px; cursor: pointer; }
</style>
</head>
<body>
<h1>ADK Custom Streaming Client</h1>
<button id="talkButton">๐ค Hold to Talk</button>
<div id="status">Status: Disconnected</div>
<div id="transcript"></div>
<script>
const APP_NAME = 'streaming_agent';
const USER_ID = 'user_' + Math.random().toString(36).substring(7);
const SESSION_ID = 'session_' + Math.random().toString(36).substring(7);
const SERVER_URL = 'http://localhost:8000';
const talkButton = document.getElementById('talkButton');
const statusDiv = document.getElementById('status');
const transcriptDiv = document.getElementById('transcript');
let websocket;
let micAudioContext;
let workletNode;
let mediaStream;
let playbackAudioContext;
let nextPlayTime = 0; // Schedules 24kHz chunks back-to-back without overlap
let sessionCreated = false;
let isConnected = false;
let isRecording = false;
function log(message) {
const p = document.createElement('p');
p.textContent = message;
transcriptDiv.appendChild(p);
transcriptDiv.scrollTop = transcriptDiv.scrollHeight;
}
// Provided: converts a Float32Array of mic samples (-1..1) into a
// Base64-encoded buffer of 16-bit little-endian PCM samples.
function float32ToBase64PCM(float32Array) {
const int16 = new Int16Array(float32Array.length);
for (let i = 0; i < float32Array.length; i++) {
const s = Math.max(-1, Math.min(1, float32Array[i]));
int16[i] = s < 0 ? s * 32768 : s * 32767;
}
const bytes = new Uint8Array(int16.buffer);
let binary = '';
for (let i = 0; i < bytes.length; i++) {
binary += String.fromCharCode(bytes[i]);
}
return btoa(binary);
}
// TODO: 1. Implement 24kHz PCM audio playback (`playAudioChunk(base64Data)`):
// a. Ensure `playbackAudioContext` exists at `{ sampleRate: 24000 }`.
// b. Normalize ADK's RFC 4648 base64url string (`-` -> `+`, `_` -> `/`)
// before calling `atob()`, then copy character codes into a `Uint8Array`.
// c. Convert each pair of little-endian bytes into signed 16-bit integers
// and divide by 32768 into a `Float32Array`.
// d. Create a mono 24000 Hz `AudioBuffer`, copy samples via `copyToChannel(floatSamples, 0)`,
// connect an `AudioBufferSourceNode` to `playbackAudioContext.destination`,
// start it at `Math.max(playbackAudioContext.currentTime, nextPlayTime)`,
// and advance `nextPlayTime = startTime + audioBuffer.duration`.
function playAudioChunk(base64Data) {
// Your implementation here
}
async function connect() {
// TODO: 2. Create the session via REST (if `!sessionCreated`) and await readiness:
// a. POST `{ session_id: SESSION_ID }` to `${SERVER_URL}/apps/${APP_NAME}/users/${USER_ID}/sessions`,
// verify `res.ok` (or `res.status === 409`), and set `sessionCreated = true`.
// b. Lazily initialize `micAudioContext` and `await micAudioContext.audioWorklet.addModule('audio-processor.js')`
// (and `await micAudioContext.resume()` if `micAudioContext.state === 'suspended'`).
// c. Open `websocket = new WebSocket(...)` to:
// `ws://localhost:8000/run_live?app_name=${APP_NAME}&user_id=${USER_ID}&session_id=${SESSION_ID}`
// d. Await `new Promise((resolve, reject) => { ... })` that resolves on the WebSocket
// `'open'` event (setting `isConnected = true`) and rejects on `'error'`, so callers
// never race before the socket and AudioWorklet are ready!
websocket.onmessage = (event) => {
// TODO: 3. Parse `JSON.parse(event.data)`, iterate over `data.content?.parts || []`,
// and call `playAudioChunk(part.inlineData.data)` for any part whose
// `part.inlineData?.mimeType` starts with `'audio/'`.
};
websocket.onclose = () => {
log('[CLIENT]: WebSocket connection closed.');
isConnected = false;
statusDiv.textContent = 'Status: Disconnected';
};
}
async function startRecording() {
try {
// Unlock audio playback directly inside the user's mousedown gesture
// so browser autoplay policy never mutes the agent's voice response!
if (!playbackAudioContext) {
playbackAudioContext = new (window.AudioContext || window.webkitAudioContext)({ sampleRate: 24000 });
}
if (playbackAudioContext.state === 'suspended') {
await playbackAudioContext.resume();
}
if (!isConnected) {
await connect();
}
mediaStream = await navigator.mediaDevices.getUserMedia({ audio: true });
const source = micAudioContext.createMediaStreamSource(mediaStream);
workletNode = new AudioWorkletNode(micAudioContext, 'audio-processor');
// TODO: 4. Stream each captured Float32Array chunk (`event.data`) to `/run_live`:
// a. Convert `event.data` to Base64 16-bit PCM with `float32ToBase64PCM(event.data)`.
// b. When `websocket?.readyState === WebSocket.OPEN`, send JSON:
// `{ blob: { data: base64Audio, mime_type: 'audio/pcm;rate=16000' } }`
workletNode.port.onmessage = (event) => {
// Your implementation here
};
source.connect(workletNode);
isRecording = true;
talkButton.textContent = '๐ด Recording... (release to send)';
log('[CLIENT]: Recording started.');
} catch (err) {
log(`[CLIENT]: Failed to start recording: ${err.message}`);
console.error(err);
}
}
function stopRecording() {
if (!isRecording) return;
isRecording = false;
talkButton.textContent = '๐ค Hold to Talk';
if (workletNode) {
workletNode.disconnect();
}
if (mediaStream) {
mediaStream.getTracks().forEach((track) => track.stop());
}
// TODO: 5. Signal end of audio stream (`{ audio_stream_end: true }`) over `websocket`
// if `websocket && websocket.readyState === WebSocket.OPEN`.
log('[CLIENT]: Recording stopped, waiting for response...');
}
talkButton.addEventListener('mousedown', startRecording);
talkButton.addEventListener('mouseup', stopRecording);
talkButton.addEventListener('mouseleave', () => {
if (isRecording) stopRecording();
});
</script>
</body>
</html>
Step 4: Run the Server and the Clientโ
-
Terminal 1 โ Run
adk api_serverfrom the parentadk-trainingdirectory:cd /path/to/your/adk-training
uv run adk api_server --allow_origins=http://localhost:8081Running from
adk-training/serves all agent packages in your workspace onhttp://localhost:8000(includingws://localhost:8000/run_live?app_name=streaming_agent&...). -
Terminal 2 โ Serve
streaming_client/on port8081:cd /path/to/your/adk-training/streaming_client
python3 -m http.server 8081
Step 5: Test Your Custom Voice Applicationโ
- Open the Client: Navigate to
http://localhost:8081in Chrome or another modern browser and grant microphone access when prompted. - Hold to Talk: Press and hold ๐ค Hold to Talk, speak a question clearly (e.g., "Hello! Give me one fun fact about outer space."), and release the button.
- Listen for the Spoken Response: Within moments,
gemini-3.8-livestreams 24kHz PCM audio chunks back over/run_live, playing smoothly through your speakers.
Having Trouble?โ
If you get stuck, check lab-solution.md or unlock the Reference Solution Vault below.
Lab Summaryโ
You have built a real-time bidirectional voice client against ADK's /run_live WebSocket API:
- Configured a Live API agent with
gemini-3.8-liveand ranuv run adk api_serverfrom the parentadk-trainingdirectory. - Unlocked Web Audio playback inside the user gesture (
await playbackAudioContext.resume()) and eliminated startup race conditions by awaiting explicit Promises for REST session creation,audioWorklet.addModule(), and WebSocketopen. - Streamed 16kHz PCM microphone input and scheduled 24kHz PCM
inlineDataoutput for gapless voice playback.
Self-Reflection Questionsโ
- Your
playAudioChunkfunction schedules each chunk atMath.max(playbackAudioContext.currentTime, nextPlayTime)instead of just callingsource.start()immediately. What audio artifact would you expect to hear if you removednextPlayTimetracking and started every chunk immediately? - The provided
audio-processor.jsposts a message to the main thread on every audio callback (small chunks, roughly 128 samples โ a few milliseconds of audio). What would be the tradeoff of batching several of these callbacks together before sending each WebSocket message, instead of sending one message per callback? - What are the benefits of using WebSockets for this application compared to the Server-Sent Events (SSE) approach used in the previous UI lab?
๐ Reference Solution Vaultโ
Official Solution Vault โ Module 30
Locked Challenge โ Active Pedagogical Socratic Gate