Build a single-file HTML/CSS/JS web app named jadoo_voice.html in Google Gemini Canvas: Jadoo Voice (جادو وائس — ذاتی اردو وائس اوور اسٹوڈیو). It creates personal Urdu voiceovers with the user's own Gemini API key (BYOK), plus an experimental portrait caption-video export. Deliver the app in Canvas with its source. Keep core app code in this one file; disclose optional external fonts and MP3 library dependencies. No external backend, proxy server, shared cloud database, or hardcoded developer key. Never ask for my API key in chat; I will enter it only in Section 1 of the finished app.
Verify the current documentation before implementing. These instructions were reviewed on 25 October 2026:
https://ai.google.dev/gemini-api/docs/generate-content/speech-generation
https://ai.google.dev/gemini-api/docs/speech-generation
https://ai.google.dev/gemini-api/docs/api-key
https://ai.google.dev/gemini-api/docs/pricing
https://ai.google.dev/gemini-api/docs/rate-limits
https://ai.google.dev/gemini-api/docs/deprecations
https://support.google.com/gemini/answer/16047321
1. Canvas runtime and model integration
Build and preview the app inside my own Canvas conversation. Test whether this preview supports direct Google API requests, local storage, playback, downloads, canvas captureStream, MediaRecorder and file sharing. Do not promise that every Canvas iframe or mobile browser supports them. If the runtime blocks an operation, name the blocked operation and keep working features available. Do not silently introduce a backend or proxy. If a downloaded local HTML copy is a useful fallback, explain its browser requirements and ask before changing the requested workflow.
Default model: gemini-3.8-flash-tts. Offer gemini-3.8-flash-lite-tts as an explicit alternative. Do not silently change models or enable paid billing. Explain in a small model-info section that gemini-2.5-flash-preview-tts has a listed earliest shutdown date of 17 November 2026, not a guaranteed final shutdown date.
This brief uses the documented generateContent REST route. Do not mix its schema with the separate Interactions API schema. POST to https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent with Content-Type: application/json and x-goog-api-key: in headers. Never put the key in a URL query string.
Send the spoken Urdu transcript in contents[0].parts[0].text and sustained delivery directions separately in contents[0].parts[0].speech_metadata.style. Include role: "user". Set generationConfig to {"responseModalities":["AUDIO"],"speechConfig":{"voiceConfig":{"voice":""}}}. For these 3.8 models, plain text is treated as a verbatim transcript; do not put stage directions into it. Support documented optional inline vocal/pause tags: , , , , . Keep tags intact during chunking and omit them from captions and spoken-word duration estimates.
2. Short Urdu audition
State that the reviewed Flash TTS language table covers over 130 languages but does not explicitly list Urdu; Flash-Lite has a different coverage table. Requested Pakistani Urdu pronunciation is not a guarantee. Preload this exact short script and invite the user to judge the result before generating a longer recording:
السلام علیکم! آج ہم اردو میں اپنا پہلا وائس اوور بنا رہے ہیں۔ پہلے ایک چھوٹا سا متن آزمائیں، پھر آواز سن کر اگلا قدم اٹھائیں۔
Do not claim that a metadata/key test proves Urdu synthesis works. Real speech generation and listening are separate acceptance checks.
3. Key controls, storage and privacy
Keep the key in memory by default. Probe localStorage with a temporary write/read/remove inside try/catch. Only if supported, enable an explicit opt-in checkbox: اسی ڈیوائس پر محفوظ کریں (Save on this device). Explain that this uses the current browser/iframe origin, not cross-device synchronization or hardware protection. If storage later fails, handle the error and use memory only. Turning the opt-in off must remove the saved key. Language preference is stored separately.
Use a masked password input, autocomplete="off", deliberate Reveal/Hide buttons (کی دکھائیں / کی چھپائیں), Test Key (کی آزمائیں), and Clear Key (کی صاف کریں). Test Key may call GET https://generativelanguage.googleapis.com/v1beta/models/{model} with x-goog-api-key. Label success as model metadata/access checked, not proof of TTS quota, billing eligibility or successful generation. Let the user run the short audition separately. Clear Key wipes the input, memory and persisted app key; it does not revoke the key in Google Cloud. Cancel pending requests when clearing credentials.
Redact the active key value and AIza... credential patterns from errors, request previews and troubleshooting logs using [REDACTED_API_KEY]. Never include secrets in source files, exported HTML, shared app data, audio/video exports, analytics or console logs. Do not turn a secret into a default input value. The key and submitted script go directly to Google's generativelanguage.googleapis.com for audio generation. Quota and billing belong to the Google Cloud project; creating another key in the same project does not add quota. Do not enable billing automatically.
Provide links to key management, project limits, pricing and data terms:
https://aistudio.google.com/app/apikey
https://aistudio.google.com/app/plan_information
https://ai.google.dev/gemini-api/docs/api-key
https://ai.google.dev/gemini-api/docs/pricing
https://ai.google.dev/gemini-api/docs/rate-limits
Before sharing an app, clear credentials and ensure no entered key or private script is embedded in source or shared data. Sharing the build prompt is the simplest way for another person to create their own copy.
4. Urdu-first interface and branding
Default lang="ur" dir="rtl". Load Noto Nastaliq Urdu non-blocking with generous line-height of at least 2.15 and vertical padding; never clip descenders. Provide an English UI / اردو انٹرفیس toggle. Preserve the script, model, voice, editable style and generated audio when changing language; persist the language preference separately from credentials.
Isolate English names, model IDs, voice IDs and numbers with dir="ltr" and unicode-bidi:isolate. Use English digits 0-9. Use کی for API key and آفیشل for official. Proofread all Urdu labels, including واضح and سیکھنے.
Use deep green #07231C and #0D352B, warm sand #F7F2E7, and gold #FFBE0B. Place the exact Urdu Ai wordmark at the physical top-right of the header: Montserrat SemiBold, font-weight 600, Urdu white #FFFFFF, Ai gold #FFBE0B, lowercase i, transparent background, no box or border.
Organize 5 numbered sections: 1 Key & Privacy; 2 Script & Audition; 3 Voice, Model & Style Direction; 4 Generation & Progress; 5 Result Player, Download & Experimental Caption Video. Include visible keyboard focus, semantic labels, 44px+ touch targets and no horizontal overflow at 375px width. Long IDs must wrap. Do not block core controls on font or optional-library loading.
5. Script, voices and style
Provide a multiline textarea with dir="auto", live character count, Urdu grapheme count using Intl.Segmenter('ur', {granularity:'grapheme'}), chunk count and a clearly labeled rough duration estimate. After generation, show the actual decoded duration. Warn when the script exceeds about 1,800 characters or spans multiple chunks. If Intl.Segmenter is unavailable, use a proper grapheme-safe fallback or explain the limitation; never silently split Urdu combining sequences.
Offer the 30 documented prebuilt voices with exact IDs and descriptors: Kore Firm; Zephyr Bright; Puck Upbeat; Charon Informative; Sulafat Warm; Fenrir Excitable; Leda Youthful; Orus Firm; Aoede Breezy; Callirrhoe Easy-going; Autonoe Bright; Enceladus Breathy; Iapetus Clear; Umbriel Easy-going; Algieba Smooth; Despina Smooth; Erinome Clear; Algenib Gravelly; Rasalgethi Informative; Laomedeia Upbeat; Achernar Soft; Alnilam Firm; Schedar Even; Gacrux Mature; Pulcherrima Forward; Achird Friendly; Zubenelgenubi Casual; Vindemiatrix Gentle; Sadachbia Lively; Sadaltager Knowledgeable. Verify these against the current docs. Offer an optional existing custom voice_... or voicekey_... input; do not imply this creates or clones a voice. Label demographic/filter groupings as editorial app descriptions, not official facts.
Expression, Pace and Requested Accent selectors should populate a free-editable speech_metadata.style field. Default to requested Pakistani Urdu delivery. Preserve deliberate user edits or ask before overwriting them. Include a collapsed sanitized JSON request preview.
6. Chunking, progress, cancellation and retries
Split at sentence boundaries (۔, ؟, !, ., ?, newline), targeting around 1,800 characters per chunk as an app choice rather than a model limit. Fall back to clause/word boundaries, then grapheme boundaries. Keep recognized angle-bracket tags intact. Use the same selected model, voice and style for all chunks.
Show Chunk N / M, completed-chunk progress and an indeterminate indicator while a request runs. Cancel via AbortController and retain completed chunks in an in-memory cache keyed by model, voice, style and chunkText. Reuse successful chunks rather than requesting them again. Explain that cache is limited to this page session; retries and requests already processed by Google may still consume quota even if the browser cancels or loses the response. Do not promise cancellation refunds or zero duplicate charges.
Retry at most 2 times with exponential backoff for transient network errors, 5xx or explicitly identified short-term rate limits. Respect Retry-After or structured retry metadata. Never loop on 400, 401/403, 404 or exhausted daily quota. If the quota category is unknown, show the error and limits link rather than guessing a reset time.
7. Audio assembly and honest checks
Read inlineData.mimeType and inspect the decoded bytes. Current unary 3.8 requests normally return a complete WAV. Do not add a second WAV header. If a single chunk is a valid WAV, preserve it. For headerless PCM, use the documented encoding, sample rate, channel count and endianness; only use 24kHz mono signed 16-bit little-endian when confirmed for the actual format. Do not infer PCM byte order from a generic MIME label alone.
Parse RIFF chunks correctly; do not assume every WAV has exactly a 44-byte header. Locate fmt and data chunks, honor padding and reject malformed data. For multiple chunks, decode and normalize to a consistent 24,000Hz mono 16-bit PCM stream, concatenate samples without container headers, then encode one WAV. Verify expected chunk count, valid container, plausible duration and non-silent amplitude. These checks do not prove every word was spoken: invite the user to listen to the whole recording and check the final sentence.
Show bilingual actionable errors for invalid requests (400, not always a bad key), credential permissions/restrictions (401/403), model/endpoint access (404), quota/rate limits (429), safety blocks, empty audio and network failures. For restrictions, link current Google key guidance rather than diagnosing every 403 as one policy change. Daily request limits reset at midnight Pacific Time where that quota applies; do not confuse them with short-term rate limits. Keep technical details sanitized.
8. Player, downloads and sharing
Show an audio controls player, actual duration and file size. Offer verified WAV download. Optionally load lamejs@1.2.1 non-blocking from cdn.jsdelivr.net for in-browser MP3 encoding. Flush the encoder; decode the completed MP3 and compare its duration with the source within max(1 second, 5%). If the library is unavailable or validation fails, retain WAV and explain the MP3 fallback. Optional fonts/library use needs internet even though app logic is in one file.
Enable native file sharing only if navigator.canShare({files:[wavFile]}) succeeds. Share the actual file, not a blob URL. Explain iPhone Save to Files, Android Downloads/Files, desktop saving, and downloading first then attaching the file in WhatsApp if native sharing is unavailable. Do not promise a particular app is installed. Revoke blob URLs only after playback/download use has finished.
9. Experimental portrait caption video
Unlock after valid audio exists. Label Experimental and Estimated Word Timing. This creates a typographic caption video from the recorded voice and script, not newly generated live-action footage. Estimate word timings from word length and punctuation within [0,audioDuration]; this is not aligned transcription. Strip non-spoken vocal tags from displayed words. Offer 720x1280 at 24fps by default and optional 1080x1920 at 30fps.
Wait for fonts before capture. Cache static layers. Render correctly shaped, connected RTL Nastaliq, highlight the current word in #FFBE0B, fade nearby words, show a context line, an audio-reactive waveform, English-digit timer and exact top-right Urdu Ai wordmark. Do not draw Urdu letters separately; preserve full-line shaping and bidi order when implementing highlighting, and visually check exported frames.
Use canvas.captureStream and a Web Audio MediaStreamDestination to combine video and audio tracks in MediaRecorder. Detect API and MIME/container support. Prefer MP4 only when supported; otherwise export the actual WebM format. Never rename WebM as MP4. Recording is approximately real time, not guaranteed faster than the audio; keep the tab active and handle interruption/cancellation. Do not require microphone access to capture already-generated audio.
Validate the final exported blob, not only the source audio: nonempty playable container, plausible duration, video dimensions and audio track. Where supported, decode its audio and check representative segments for non-silent samples. decodeAudioData may reject a video container or codec even when audio is present; decoding failure is not proof of silence. Use a supported media/demux-and-decode or playback-analysis route when available. If automatic verification cannot be completed, clearly label the export as requiring playback verification, retain the WAV, and ask the user to listen before using it; never claim it passed automatically. If audio is demonstrably silent or missing, retry once with a corrected gain/track route; if still invalid, reject the video as successful and preserve the audio. Always offer a player to check the saved result and final sentence.
10. Offline diagnostics and handover
Include a collapsed diagnostic drawer for simulated single-chunk WAV, simulated 3-chunk PCM assembly and simulated 400/403/404/429 errors without a key. Clearly label all simulated audio and results; they are not live Gemini synthesis. Also test cancel/resume caching, no repeated successful chunk requests, correct WAV headers, blocked storage, unavailable MP3 library, language toggle without data loss and 375px layout.
Report which tests were real, simulated or still require the user's key/device. Do not invent successful speech generation, Canvas network access, mobile exports or video audio checks. Deliver the Canvas app, its single-file source, optional dependency versions and instructions to reopen it. Complete non-network parts if no key is available. Never request the secret key in chat, publish a shared key or deploy an external service.