Speech Synthesis

by Ben Gillbanks

HTML

<h1>Speech Test</h1>

JavaScript

beep8 = {};

beep8.speak = (text, options = {}) => {
	if (!window.speechSynthesis) return;

	const utterance = new SpeechSynthesisUtterance(text);

	// Optional settings
	utterance.pitch = options.pitch ?? 1;
	utterance.rate = options.rate ?? 1;
	utterance.volume = options.volume ?? 1;

	// Pick a voice if one is specified
	if (options.voice) {
		const voices = speechSynthesis.getVoices();
		const voice = voices.find(v => v.name === options.voice);
		if (voice) utterance.voice = voice;
	}

	speechSynthesis.speak(utterance);
};


beep8.speak("Welcome to Beep8!");

beep8.speak("Level complete!", {
	pitch: 1.2,
	rate: 0.9,
	volume: 0.8
});

beep8.speak("Tumble", {
	pitch: 0.2,
	rate: 0.5,
	volume: 1
});