Created
April 13, 2023 17:56
-
-
Save bfolkens/e1643934b5cde9a675607d78a1d06497 to your computer and use it in GitHub Desktop.
HTML5 SpeechRecognition for Alpine
This file contains 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
export default function (Alpine) { | |
const recognizer = new window.SpeechRecognition() | |
recognizer.lang = navigator.language | |
recognizer.continuous = false | |
recognizer.interimResults = true | |
Alpine.store('speechRecognizer', { | |
state: 'stopped', | |
error: null, | |
api: recognizer | |
}) | |
Alpine.directive('speech-recognition', (el, { expression }, { evaluate }) => { | |
data().api.onstart = (event) => { | |
setState('running') | |
} | |
data().api.onend = (event) => { | |
setState('stopped') | |
} | |
data().api.onerror = (event) => { | |
data().error = event.message | |
setState('stopped') | |
} | |
data().api.onresult = (event) => { | |
evaluate(`${expression} = '${event.results[0][0].transcript}'`) | |
} | |
}) | |
Alpine.magic('speechRecognition', (el, { Alpine }) => { | |
return { | |
start() { | |
setState('starting') | |
data().api.start() | |
}, | |
stop() { | |
setState('stopping') | |
data().api.stop() | |
}, | |
abort() { | |
setState('aborting') | |
data().api.abort() | |
}, | |
toggle() { | |
if (getState() == 'stopped') { | |
this.start() | |
} else if (getState() == 'running') { | |
this.stop() | |
} else { | |
this.abort() | |
} | |
}, | |
available() { | |
return ('SpeechRecognition' in window) | |
} | |
} | |
}) | |
function data() { | |
return Alpine.store('speechRecognizer') | |
} | |
function getState() { | |
return data().state | |
} | |
function setState(value) { | |
data().state = value | |
} | |
} | |
window.SpeechRecognition = window.webkitSpeechRecognition || window.SpeechRecognition |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment