Files
order_site/apps/frontend/src/utils/worker-speech.ts
T

29 lines
978 B
TypeScript

const WORKER_SPEECH_KEY = 'order-site-worker-new-order-speech'
export function isWorkerSpeechEnabled() {
return window.localStorage.getItem(WORKER_SPEECH_KEY) === '1'
}
export function setWorkerSpeechEnabled(enabled: boolean) {
window.localStorage.setItem(WORKER_SPEECH_KEY, enabled ? '1' : '0')
}
/** 用浏览器语音合成播报一段中文;不支持或被浏览器拦截时静默失败。 */
export function speakWorkerText(text: string) {
if (!('speechSynthesis' in window)) return
try {
window.speechSynthesis.cancel()
const utterance = new SpeechSynthesisUtterance(text)
utterance.lang = 'zh-CN'
utterance.rate = 1
utterance.volume = 1
const zhVoice = window.speechSynthesis
.getVoices()
.find((voice) => voice.lang.toLowerCase().startsWith('zh'))
if (zhVoice) utterance.voice = zhVoice
window.speechSynthesis.speak(utterance)
} catch {
// 部分浏览器禁用语音合成,不影响页面功能。
}
}