Created
October 31, 2020 03:06
-
-
Save wobsoriano/7df1901f528e0e9350f14ce841b04fed to your computer and use it in GitHub Desktop.
Speech Recognition as a Vue 3 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 { watch, ref } from "vue"; | |
const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition; | |
const recognition = new SpeechRecognition(); | |
recognition.continuous = true; | |
recognition.interimResults = true; | |
recognition.lang = "en-US"; | |
export default function useSpeechRecognition() { | |
const isListening = ref(false); | |
const note = ref(""); | |
const error = ref(null); | |
const handleListen = () => { | |
if (isListening.value) { | |
recognition.start(); | |
} else { | |
recognition.stop(); | |
} | |
}; | |
const toggleListening = () => { | |
isListening.value = !isListening.value; | |
}; | |
recognition.onresult = (event) => { | |
const transcript = Array.from(event.results) | |
.map((result) => result[0]) | |
.map((result) => result.transcript) | |
.join(""); | |
note.value = transcript; | |
}; | |
recognition.onerror = (event) => { | |
error.value = event.error; | |
}; | |
watch(isListening, () => { | |
handleListen(); | |
}); | |
return { | |
toggleListening, | |
note, | |
error | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment