diff --git a/frontend/src/composables/useSpeechRecognition.ts b/frontend/src/composables/useSpeechRecognition.ts new file mode 100644 index 00000000..39a68a2e --- /dev/null +++ b/frontend/src/composables/useSpeechRecognition.ts @@ -0,0 +1,156 @@ +import { ref, computed, onBeforeUnmount, type Ref } from 'vue'; + +export type SpeechRecognitionErrorKey = + | 'chat.voiceNotSupported' + | 'chat.voiceRequiresHttps' + | 'chat.voicePermissionDenied' + | 'chat.voiceNoSpeech' + | 'chat.voiceAudioCapture' + | 'chat.voiceNetworkError' + | 'chat.voiceServiceNotAllowed' + | 'chat.voiceRecognitionFailed'; + +type SpeechRecognitionCtor = new () => SpeechRecognition; + +const getSpeechRecognitionCtor = (): SpeechRecognitionCtor | null => { + if (typeof window === 'undefined') return null; + const w = window as Window & { + SpeechRecognition?: SpeechRecognitionCtor; + webkitSpeechRecognition?: SpeechRecognitionCtor; + }; + return w.SpeechRecognition || w.webkitSpeechRecognition || null; +}; + +export const mapLocaleToSpeechLang = (locale: string): string => { + const map: Record = { + 'zh-CN': 'zh-CN', + 'zh-TW': 'zh-TW', + en: 'en-US', + th: 'th-TH', + }; + return map[locale] || 'zh-CN'; +}; + +const isSecureContextForSpeech = (): boolean => { + if (typeof window === 'undefined') return false; + if (window.isSecureContext) return true; + const host = window.location.hostname; + return host === 'localhost' || host === '127.0.0.1'; +}; + +/** 语音不可用时的提示 key;HTTPS/localhost 且浏览器有 API 时返回 null */ +export const getVoiceUnavailableErrorKey = (): SpeechRecognitionErrorKey | null => { + if (!isSecureContextForSpeech()) return 'chat.voiceRequiresHttps'; + if (!getSpeechRecognitionCtor()) return 'chat.voiceNotSupported'; + return null; +}; + +const mapErrorToKey = (error: string): SpeechRecognitionErrorKey => { + switch (error) { + case 'not-allowed': + return 'chat.voicePermissionDenied'; + case 'service-not-allowed': + return 'chat.voiceServiceNotAllowed'; + case 'no-speech': + return 'chat.voiceNoSpeech'; + case 'audio-capture': + return 'chat.voiceAudioCapture'; + case 'network': + return 'chat.voiceNetworkError'; + default: + return 'chat.voiceRecognitionFailed'; + } +}; + +export function useSpeechRecognition(options: { + lang: Ref; + onResult: (text: string) => void; + onError: (key: SpeechRecognitionErrorKey) => void; +}) { + const isListening = ref(false); + const isSupported = computed(() => getVoiceUnavailableErrorKey() === null); + + let recognition: SpeechRecognition | null = null; + let baseText = ''; + + const stop = () => { + if (recognition) { + try { + recognition.abort(); + } catch { + // ignore abort errors + } + recognition = null; + } + isListening.value = false; + }; + + const start = (existingText = '') => { + if (isListening.value) return; + + const unavailable = getVoiceUnavailableErrorKey(); + if (unavailable) { + options.onError(unavailable); + return; + } + + const Ctor = getSpeechRecognitionCtor()!; + + stop(); + baseText = existingText; + + const instance = new Ctor(); + instance.continuous = true; + instance.interimResults = true; + instance.lang = mapLocaleToSpeechLang(options.lang.value); + + instance.onstart = () => { + isListening.value = true; + }; + + instance.onresult = (event: SpeechRecognitionEvent) => { + let sessionTranscript = ''; + for (let i = 0; i < event.results.length; i++) { + sessionTranscript += event.results[i]?.[0]?.transcript || ''; + } + options.onResult(`${baseText}${sessionTranscript}`); + }; + + instance.onerror = (event: SpeechRecognitionErrorEvent) => { + if (event.error === 'aborted') return; + options.onError(mapErrorToKey(event.error)); + stop(); + }; + + instance.onend = () => { + isListening.value = false; + recognition = null; + }; + + recognition = instance; + try { + recognition.start(); + } catch { + options.onError('chat.voiceRecognitionFailed'); + stop(); + } + }; + + const toggle = (existingText = '') => { + if (isListening.value) { + stop(); + return; + } + start(existingText); + }; + + onBeforeUnmount(stop); + + return { + isListening, + isSupported, + start, + stop, + toggle, + }; +} diff --git a/frontend/src/i18n.ts b/frontend/src/i18n.ts index 2d1061c1..b9a988d3 100644 --- a/frontend/src/i18n.ts +++ b/frontend/src/i18n.ts @@ -1250,6 +1250,16 @@ const messages = { welcomeTitle: 'Hello, I am Hexin AI Digital Human', askAnything: 'Ask me anything...', voiceFeature: 'Voice feature', + voiceListening: 'Listening...', + voiceStop: 'Stop voice input', + voiceNotSupported: 'Voice input is not supported in this browser', + voiceRequiresHttps: 'Voice input requires HTTPS or localhost access', + voicePermissionDenied: 'Microphone permission denied. Allow it in browser settings', + voiceNoSpeech: 'No speech detected. Please try again', + voiceAudioCapture: 'Unable to access microphone', + voiceNetworkError: 'Voice recognition network error', + voiceServiceNotAllowed: 'Voice recognition service is not allowed', + voiceRecognitionFailed: 'Voice recognition failed. Please try again', collapseBrowser: 'Collapse Browser', openBrowser: 'Open Browser', kb: { @@ -2703,6 +2713,16 @@ const messages = { welcomeTitle: '你好,我是和信AI数字人', askAnything: '问我任何事...', voiceFeature: '语音功能', + voiceListening: '正在聆听…', + voiceStop: '停止语音输入', + voiceNotSupported: '当前浏览器不支持语音输入', + voiceRequiresHttps: '语音输入需要 HTTPS 或 localhost 访问', + voicePermissionDenied: '麦克风权限被拒绝,请在浏览器设置中允许', + voiceNoSpeech: '未检测到语音,请重试', + voiceAudioCapture: '无法访问麦克风', + voiceNetworkError: '语音识别网络错误', + voiceServiceNotAllowed: '不允许使用语音识别服务', + voiceRecognitionFailed: '语音识别失败,请重试', collapseBrowser: '收起浏览器', openBrowser: '打开浏览器', kb: { @@ -4015,6 +4035,16 @@ const messages = { welcomeTitle: '你好,我是和信AI數字人', askAnything: '問我任何事...', voiceFeature: '語音功能', + voiceListening: '正在聆聽…', + voiceStop: '停止語音輸入', + voiceNotSupported: '目前瀏覽器不支援語音輸入', + voiceRequiresHttps: '語音輸入需要 HTTPS 或 localhost 存取', + voicePermissionDenied: '麥克風權限被拒絕,請在瀏覽器設定中允許', + voiceNoSpeech: '未偵測到語音,請重試', + voiceAudioCapture: '無法存取麥克風', + voiceNetworkError: '語音辨識網路錯誤', + voiceServiceNotAllowed: '不允許使用語音辨識服務', + voiceRecognitionFailed: '語音辨識失敗,請重試', collapseBrowser: '收起瀏覽器', openBrowser: '打開瀏覽器', kb: { @@ -5244,6 +5274,16 @@ const messages = { welcomeTitle: 'สวัสดี ฉันคือ AI Digital Human ของ Hexin', askAnything: 'ถามฉันได้ทุกเรื่อง...', voiceFeature: 'ฟีเจอร์เสียง', + voiceListening: 'กำลังฟัง...', + voiceStop: 'หยุดป้อนข้อมูลด้วยเสียง', + voiceNotSupported: 'เบราว์เซอร์นี้ไม่รองรับการป้อนข้อมูลด้วยเสียง', + voiceRequiresHttps: 'การป้อนข้อมูลด้วยเสียงต้องใช้ HTTPS หรือ localhost', + voicePermissionDenied: 'ไม่ได้รับอนุญาตให้ใช้ไมโครโฟน โปรดอนุญาตในการตั้งค่าเบราว์เซอร์', + voiceNoSpeech: 'ไม่พบเสียงพูด โปรดลองอีกครั้ง', + voiceAudioCapture: 'ไม่สามารถเข้าถึงไมโครโฟนได้', + voiceNetworkError: 'เกิดข้อผิดพลาดเครือข่ายในการรู้จำเสียง', + voiceServiceNotAllowed: 'ไม่อนุญาตให้ใช้บริการรู้จำเสียง', + voiceRecognitionFailed: 'การรู้จำเสียงล้มเหลว โปรดลองอีกครั้ง', collapseBrowser: 'ย่อเบราว์เซอร์', openBrowser: 'เปิดเบราว์เซอร์', kb: { diff --git a/frontend/src/types/speech-recognition.d.ts b/frontend/src/types/speech-recognition.d.ts new file mode 100644 index 00000000..239add32 --- /dev/null +++ b/frontend/src/types/speech-recognition.d.ts @@ -0,0 +1,45 @@ +interface SpeechRecognitionAlternative { + transcript: string; + confidence: number; +} + +interface SpeechRecognitionResult { + readonly isFinal: boolean; + readonly length: number; + item(index: number): SpeechRecognitionAlternative; + [index: number]: SpeechRecognitionAlternative; +} + +interface SpeechRecognitionResultList { + readonly length: number; + item(index: number): SpeechRecognitionResult; + [index: number]: SpeechRecognitionResult; +} + +interface SpeechRecognitionEvent extends Event { + readonly resultIndex: number; + readonly results: SpeechRecognitionResultList; +} + +interface SpeechRecognitionErrorEvent extends Event { + readonly error: string; + readonly message: string; +} + +interface SpeechRecognition extends EventTarget { + continuous: boolean; + interimResults: boolean; + lang: string; + start(): void; + stop(): void; + abort(): void; + onstart: ((this: SpeechRecognition, ev: Event) => void) | null; + onend: ((this: SpeechRecognition, ev: Event) => void) | null; + onresult: ((this: SpeechRecognition, ev: SpeechRecognitionEvent) => void) | null; + onerror: ((this: SpeechRecognition, ev: SpeechRecognitionErrorEvent) => void) | null; +} + +interface Window { + SpeechRecognition?: new () => SpeechRecognition; + webkitSpeechRecognition?: new () => SpeechRecognition; +} diff --git a/frontend/src/views/ChatView.vue b/frontend/src/views/ChatView.vue index 9f4695ad..ad2e1f0c 100644 --- a/frontend/src/views/ChatView.vue +++ b/frontend/src/views/ChatView.vue @@ -1,4 +1,4 @@ -