Created
October 31, 2020 03:04
-
-
Save wobsoriano/1626cb35db4b232664a791f9006b0509 to your computer and use it in GitHub Desktop.
Text to Speech as a Vue hook
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
| 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