DEV Community

WDSEGA
WDSEGA

Posted on

Text to Speech

The browser can speak natively — no backend API needed. The Web Speech API's SpeechSynthesis interface makes text-to-speech possible with 3 lines of code — but a production-grade implementation needs voice selection, rate control, queue management, and browser compat handling.

What Is It

Text to Speech (TTS) converts text into spoken audio. The Web Speech API has been natively supported since Chrome 33 — completely free, offline-capable, zero dependencies.

Key Technical Points

  1. onvoiceschanged: Chrome loads voice list asynchronously, must listen for this event
  2. cancel before speak: Consecutive speak() calls queue up — cancel() first
  3. autoplay policy: Safari/Chrome require user interaction before playing
  4. Long text truncation: Chrome ~15s limit, need chunking
  5. Rate control: Range 0.1-10, recommended 0.5-2

Common Pitfalls

  • voiceschanged not firing: Use setTimeout retry on Safari
  • Pause/resume bug: Some Chrome versions have bugs, use cancel()+re-speak() fallback
  • Missing Chinese voice: Linux may lack voice packs, detect and prompt
  • iOS restrictions: Each speak() must be triggered by user gesture
  • Memory leak: Manually null utterance references in callbacks

更多Web组件,请访问 Web组件字典


Read the full bilingual version at Deskless Daily.

Top comments (0)