Skip to content

Instantly share code, notes, and snippets.

@wobsoriano
Created October 31, 2020 03:04
Show Gist options
  • Save wobsoriano/1626cb35db4b232664a791f9006b0509 to your computer and use it in GitHub Desktop.
Save wobsoriano/1626cb35db4b232664a791f9006b0509 to your computer and use it in GitHub Desktop.
Text to Speech as a Vue hook
import { onMounted, ref } from 'vue';
export default function useTextToSpeech() {
const isLoading = ref(true);
const isSupported = ref(null);
const supportedVoices = ref([]);
const message = ref(null);
const checkIfSupported = () => {
isLoading.value = true;
if ('speechSynthesis' in window) {
isSupported.value = true;
message.value = new SpeechSynthesisUtterance();
supportedVoices.value = window.speechSynthesis.getVoices();
} else {
isSupported.value = false;
}
isLoading.value = false;
}
onMounted(() => {
checkIfSupported();
});
const say = (text) => {
window.speechSynthesis.speak(text);
}
const setVoice = (voiceIndex) => {
message.value.voice = supportedVoices.value[voiceIndex];
}
return {
isLoading,
isSupported,
supportedVoices,
setVoice,
say
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment