Last active
March 9, 2021 09:15
-
-
Save trouni/7750caa968b4494bd47a2821964444c8 to your computer and use it in GitHub Desktop.
Simple implementation of a speechSynthesis object
This file contains hidden or 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
function SynthVoice(options = {}) { | |
this.synth = window.speechSynthesis; | |
this.utterance = new SpeechSynthesisUtterance() | |
// Default options | |
this.options = { voiceURI: "Google US English" } | |
Object.assign(this.options, options) | |
this.getVoices = () => { | |
// Need to wait until getVoices() actually returns some results | |
return new Promise(resolve => { | |
var fetchVoicesInterval = setInterval(() => { | |
if (this.synth.getVoices().length !== 0) { | |
resolve(this.synth.getVoices()); | |
clearInterval(fetchVoicesInterval); | |
} | |
}, 10); | |
}) | |
} | |
this.initVoice = async (options = {}) => { | |
if (!this.voices) this.voices = await this.getVoices() | |
const voiceURI = options.voiceURI || this.options.voiceURI | |
this.options.voice = this.voices.find((el) => el.voiceURI === voiceURI); | |
// Assign default options | |
Object.assign(this.utterance, this.options) | |
// Override default options | |
if (Object.keys(options).length) Object.assign(this.utterance, options) | |
}; | |
this.say = async (message, options = {}) => { | |
await this.initVoice(options) | |
this.utterance.text = message | |
this.synth.speak(this.utterance); | |
} | |
this.initVoice() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
USAGE
Initialize the SpeechSynthesis object
Initialize with default options (Google US English voice)
Set voice options during initialization
Speak
Simply use:
You can also override options at the utterance level: