Skip to content

Instantly share code, notes, and snippets.

@kevinlin1
Last active Mar 28, 2022
Embed
What would you like to do?
Caption your speech on any website using the Web Speech API
javascript:(() => {
div = document.createElement('div');
div.style.backgroundColor = 'rgba(0,0,0,0.75)';
div.style.bottom = '5%';
div.style.left = '10%';
div.style.maxWidth = '80%';
div.style.position = 'fixed';
div.style.zIndex = '10000';
let caption, timeoutID;
recognition = new webkitSpeechRecognition();
recognition.continuous = false;
recognition.interimResults = true;
recognition.lang = 'en-US';
recognition.onresult = event => {
let transcript = '';
for (let i = 0; i < event.results.length; i += 1) {
transcript += event.results[i][0].transcript;
}
if (!div.contains(caption)) {
caption = document.createElement('p');
caption.style.color = 'white';
caption.style.fontFamily = 'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif';
caption.style.fontSize = '3vh';
caption.style.margin = '0';
caption.style.padding = '0.5vh 1vh';
div.appendChild(caption);
} else {
clearTimeout(timeoutID);
}
caption.innerHTML = transcript.replace(/\n/g, '<br>');
timeoutID = setTimeout(() => caption.remove(), 3000);
};
recognition.onend = event => recognition.start();
document.body.appendChild(div);
recognition.start();
div.onclick = event => {
recognition.onend = event => {};
recognition.stop();
div.remove();
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment