A userscript that adds text-to-speech functionality to any webpage. Select text to have it read aloud.
- Automatically detects text selection
- Uses browser's preferred language
- Play/Pause/Resume controls
The script utilizes the Javascript Web Speech API's SpeechSynthesisUtterance interface for text-to-speech functionality. Here's a detailed breakdown of the key components:
const speech = window.speechSynthesis;
const utterance = new SpeechSynthesisUtterance(text);utterance.text: The text to be spokenutterance.lang: Language of the speech (e.g., "en-US", "es-ES")utterance.voice: The SpeechSynthesisVoice to useutterance.volume: Volume from 0 to 1 (default: 1)utterance.rate: Speech rate from 0.1 to 10 (default: 1)utterance.pitch: Pitch from 0 to 2 (default: 1)
utterance.onstart = () => { /* Speech starts */ }
utterance.onend = () => { /* Speech ends */ }
utterance.onpause = () => { /* Speech is paused */ }
utterance.onresume = () => { /* Speech resumes */ }
utterance.onerror = (event) => { /* Error occurs */ }The script implements a sophisticated voice selection system:
const voices = speechSynthesis.getVoices();
const preferredVoice = voices.find(voice =>
voice.lang.toLowerCase() === preferredLanguage.toLowerCase()
);- First attempts exact language match
- Falls back to base language match
- Defaults to system voice if no match found
The Web Speech API is supported in:
- Chrome 33+
- Edge 14+
- Safari 7+
- Firefox 49+
- Opera 21+
- Speech synthesis quality varies by browser and the host system
- Voice availability depends on system language packs
- Some browsers limit speech duration
- Mobile browser support may be limited
Common issues and solutions:
-
No Sound
- Check system volume
- Verify browser permissions
- Ensure voice pack is installed
-
Wrong Language
- Check browser language settings
- Install appropriate language pack
- Verify voice availability
-
Performance Issues
- Reduce text selection size
- Adjust speech rate
- Check browser load