import VolumeTTS from './VolumeTTS.js'; /** * TTS使用示例和最佳实践 */ class TTSExample { constructor() { this.tts = null; this.init(); } // 初始化TTS init() { try { // 创建TTS实例,可以传入自定义参数 this.tts = new VolumeTTS({ lang: "zh-CN", speed: 0.8, // 语速稍慢,提高识别率 pitch: 1.0, // 音调正常 volume: 1.0 // 音量最大 }); console.log('TTS实例创建成功'); // 监听TTS状态变化 this._monitorTTSStatus(); } catch (error) { console.error('TTS初始化失败:', error); } } // 监听TTS状态 _monitorTTSStatus() { // 定期检查TTS状态 setInterval(() => { if (this.tts) { const status = this.tts.getStatus(); console.log('TTS状态:', status); // 如果TTS不可用且重试次数未达到上限,尝试重新初始化 if (!status.isInitialized && status.retryCount < status.maxRetries) { console.log('TTS不可用,尝试重新初始化...'); this.tts.init(); } } }, 10000); // 每10秒检查一次 } // 基础播报示例 speakBasic(text) { if (!this.tts) { console.error('TTS未初始化'); return; } if (!text) { console.warn('播报文本为空'); return; } console.log('开始播报:', text); this.tts.speak(text); } // 播报订单信息 speakOrder(orderInfo) { if (!orderInfo) return; const text = `订单号${orderInfo.orderNo},商品${orderInfo.productName},数量${orderInfo.quantity}件`; this.speakBasic(text); } // 播报扫描结果 speakScanResult(barcode, productName) { const text = `扫描到条码${barcode},商品${productName}`; this.speakBasic(text); } // 播报错误信息 speakError(errorMsg) { const text = `错误:${errorMsg}`; this.speakBasic(text); } // 播报成功信息 speakSuccess(successMsg) { const text = `成功:${successMsg}`; this.speakBasic(text); } // 播报数字(会自动转换为中文) speakNumber(number) { const text = `数字${number}`; this.speakBasic(text); } // 停止播报 stop() { if (this.tts) { this.tts.stop(); } } // 销毁TTS实例 destroy() { if (this.tts) { this.tts.destroy(); this.tts = null; } } // 获取TTS状态 getStatus() { return this.tts ? this.tts.getStatus() : null; } // 检查TTS是否可用 isAvailable() { return this.tts ? this.tts.isAvailable() : false; } // 设置自定义播报参数 setCustomOptions(opts) { if (this.tts) { this.tts.setCustomOpts(opts); } } // 清除自定义参数 clearCustomOptions() { if (this.tts) { this.tts.clearCustomOpts(); } } } // 导出单例实例 const ttsExample = new TTSExample(); export default ttsExample; // 使用示例: /* // 在页面中使用 import ttsExample from '@/utils/TTSExample.js'; // 播报文本 ttsExample.speakBasic('欢迎使用书嗨系统'); // 播报订单信息 ttsExample.speakOrder({ orderNo: '12345', productName: '图书', quantity: 5 }); // 播报扫描结果 ttsExample.speakScanResult('123456789', '图书名称'); // 播报错误 ttsExample.speakError('网络连接失败'); // 播报成功 ttsExample.speakSuccess('操作完成'); // 播报数字(会自动转换为中文) ttsExample.speakNumber('123'); // 停止播报 ttsExample.stop(); // 检查状态 const status = ttsExample.getStatus(); console.log('TTS状态:', status); // 销毁实例(页面销毁时调用) ttsExample.destroy(); */