Skip to content

Instantly share code, notes, and snippets.

@tomhodgins
Created November 5, 2024 19:50
Show Gist options
  • Save tomhodgins/7181b71dab41d5a1e83f1612806117c6 to your computer and use it in GitHub Desktop.
Save tomhodgins/7181b71dab41d5a1e83f1612806117c6 to your computer and use it in GitHub Desktop.
function speak(
text = '',
options = {
volume: 1, // 0-1
rate: 1.25, // 0.1-10
pitch: 1, // 0-2
lang: 'en-US',
// voice: 'Catherine'
voice: 'Karen'
}
) {
const utterance = new SpeechSynthesisUtterance(text)
if (options.voice !== '') {
const matchingVoice = speechSynthesis.getVoices().find(voice => voice.name.includes(options.voice))
if (matchingVoice !== undefined) {
utterance.voice = matchingVoice
}
}
delete options.voice
Object.assign(utterance, options)
return speechSynthesis.speak(utterance)
}
document.querySelectorAll('p, li').forEach(tag => tag.addEventListener('click', event => {
tag.style.backgroundColor = '#ffa'
window.setTimeout(() => tag.style.transition = 'background-color 5s ease-in-out')
window.setTimeout(() => tag.style.backgroundColor = '', 5000)
speak(event.target.textContent.trim())
}))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment