Skip to content

Instantly share code, notes, and snippets.

@lyda
Created April 20, 2020 18:16
Show Gist options
  • Save lyda/032010858a80e51980ce98f98eb384d9 to your computer and use it in GitHub Desktop.
Save lyda/032010858a80e51980ce98f98eb384d9 to your computer and use it in GitHub Desktop.
The code I use to add a "listen to article" link on my blog
/**
* Chunkify
* Google Chrome Speech Synthesis Chunking Pattern
* Fixes inconsistencies with speaking long texts in speechUtterance objects
* Licensed under the MIT License
*
* Peter Woolley and Brett Zamir
* https://gist.github.com/woollsta/2d146f13878a301b36d7
* Modified by Haaris for bug fixes
* https://gist.github.com/hsed/ef4a2d17f76983588cb6d2a11d4566d6
* Modified by me.
*/
function copyUtterance(utt, text) {
var newUtt = new SpeechSynthesisUtterance(text)
var prop
for (prop in utt) {
if (utt.hasOwnProperty(prop) && prop !== 'text') {
newUtt[prop] = utt[prop]
}
}
return newUtt
}
function speechUtteranceChunker(utt) {
var newUtt
var lines = utt.text.split(/\n+/)
var i
for (i in lines) {
var chunks = lines[i].split(/\.\s+/)
var j
for (j in chunks) {
var newUtt = copyUtterance(utt, chunks[j])
newUtt.addEventListener('end', function () {
if (speechUtteranceChunker.cancel) {
speechUtteranceChunker.cancel = false
return
}
})
// IMPORTANT!! Do not remove console.log() call. Logging the object
// out fixes some onend firing issues.
console.log(newUtt)
// Placing the speak invocation inside a callback fixes ordering
// and onend issues.
//setTimeout(function () { speechSynthesis.speak(newUtt) }, 0)
speechSynthesis.speak(newUtt)
}
}
var newUtt = copyUtterance(
new SpeechSynthesisUtterance(), "Thank you for listening."
)
newUtt.onend = function(event) {
controlsDisplay("none")
}
console.log(newUtt)
speechSynthesis.speak(newUtt)
}
function toggle_pause() {
var pause = document.getElementById("toggle")
if (pause.innerText == "pause") {
speechSynthesis.pause()
pause.innerText = "resume"
} else {
speechSynthesis.resume()
pause.innerText = "pause"
}
}
function stop_button() {
speechSynthesis.cancel()
controlsDisplay("none")
}
function controlsDisplay(display) {
document.getElementById("controls").style.display = display
}
function listen_to_article() {
var article = [
document.getElementById("speak-title").innerText,
document.getElementById("speak-article").innerText,
].join(".\n")
var msg = new SpeechSynthesisUtterance(article)
var voices = window.speechSynthesis.getVoices()
msg.voice = voices[10]
msg.voiceURI = 'native'
msg.volume = 1
msg.rate = 0.8
msg.pitch = 1
msg.lang = 'en-US'
speechUtteranceChunker(msg)
controlsDisplay("inline")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment