Skip to content

Instantly share code, notes, and snippets.

@trouni
Last active March 9, 2021 09:15
Show Gist options
  • Save trouni/7750caa968b4494bd47a2821964444c8 to your computer and use it in GitHub Desktop.
Save trouni/7750caa968b4494bd47a2821964444c8 to your computer and use it in GitHub Desktop.
Simple implementation of a speechSynthesis object
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()
}
@trouni
Copy link
Author

trouni commented Mar 9, 2021

USAGE

Initialize the SpeechSynthesis object

Initialize with default options (Google US English voice)

var voice = new SynthVoice()

Set voice options during initialization

var voice = new SynthVoice({voiceURI: "Google UK English Female", rate: 0.9})

Speak

Simply use:

voice.say("Hello World!")

You can also override options at the utterance level:

voice.say("Hello World!", {voiceURI: "Google UK English Female", volume: 0.5})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment