/** * TTS语音服务 */ export class TTSService { private static instance: TTSService | null = null private constructor() {} static getInstance(): TTSService { if (!TTSService.instance) { TTSService.instance = new TTSService() } return TTSService.instance } /** * 播放语音查询结果 */ async playQueryResult(text: string): Promise { try { // 使用Web Speech API if ('speechSynthesis' in window) { this.playWithWebSpeech(text) } else { // 回退方案:使用第三方TTS服务 await this.playWithExternalTTS(text) } } catch (error) { console.error('TTS播放失败:', error) throw new Error('语音播放失败') } } /** * 使用Web Speech API */ private playWithWebSpeech(text: string): void { const utterance = new SpeechSynthesisUtterance(text) utterance.lang = 'zh-CN' utterance.rate = 0.9 utterance.pitch = 1 utterance.volume = 1 speechSynthesis.speak(utterance) } /** * 使用外部TTS服务(可替换为实际的服务API) */ private async playWithExternalTTS(text: string): Promise { // 这里可以集成百度TTS、阿里云TTS等服务 // 目前模拟实现 return new Promise((resolve) => { console.log('外部TTS服务调用:', text) setTimeout(resolve, 1000) }) } /** * 停止语音播放 */ stop(): void { if ('speechSynthesis' in window) { speechSynthesis.cancel() } } /** * 检查浏览器是否支持语音合成 */ isSupported(): boolean { return 'speechSynthesis' in window } } export const ttsService = TTSService.getInstance()