Created
September 11, 2018 10:17
-
-
Save phongjalvn/fe7f561b601a6e1b3fc560f15ff864a4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let synth; | |
let voice; | |
let attempts = 0; | |
function loadVoices() { | |
attempts++; | |
const voices = synth.getVoices(); | |
if (voices.length) { | |
voice = voices.find(_voice => /ja[-_]JP/.test(_voice.lang)); | |
} | |
if (!voice) { | |
if (attempts < 10) { | |
setTimeout(() => { | |
loadVoices(); | |
}, 250); | |
} else { | |
console.error('`ja-JP` voice not found.'); | |
} | |
} | |
} | |
if ('speechSynthesis' in window) { | |
synth = window.speechSynthesis; | |
loadVoices(); | |
} | |
function speak(text) { | |
if (!synth || synth.speaking) { | |
return; | |
} | |
// …,..., ___ | |
const output = text.replace(/(…|[._]{2,})/, ''); | |
const utterance = new SpeechSynthesisUtterance(output); | |
utterance.addEventListener('error', error => console.error(error)); | |
utterance.lang = 'ja-JP'; | |
utterance.pitch = 1; | |
utterance.rate = 1; | |
utterance.voice = voice; | |
utterance.volume = 1; | |
synth.speak(utterance); | |
} | |
export default { | |
speak, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment