class VolumeTTS { ttsParams = { lang: "zh-CN", speed: 1, // 将 0-10 转换为 0-1 pitch: 1, // 将 0-10 转换为 0-1 volume: 1, }; TTSModule; customOpts = null; // 自定义的opts参数 platform = uni.getSystemInfoSync().platform; constructor(opts) { let audioConfig = uni.getStorageSync("audioConfig"); if (opts) { this.ttsParams = opts; } else if (audioConfig) { this.ttsParams = { lang: "zh-CN", speed: audioConfig.audioSpeed / 10, pitch: audioConfig.audioVolume, volume: 1, }; } // #ifdef APP-PLUS this.init(); // #endif } init() { this.TTSModule = uni.requireNativePlugin("nrb-tts-plugin"); this.TTSModule && this.TTSModule.init( { lang: "zh", country: "CN", }, (res) => { if (res.success == 0) { console.log("TTS初始化成功"); } } ); } //加一个text的预处理,将text中的数字替换成 零一二三四五六七八九十 preprocessText(text) { // 将text中的数字替换成 零一二三四五六七八九十 const digitMap = { 0: "零", 1: "一", 2: "二", 3: "三", 4: "四", 5: "五", 6: "六", 7: "七", 8: "八", 9: "九", }; return text.replace(/\d+/g, (match) => { // 逐字符替换所有数字,包括10 return match .split("") .map((digit) => digitMap[digit] || digit) .join(""); }); } /** * 设置自定义的opts参数 * @param {Object} opts - 自定义的opts参数 */ setCustomOpts(opts) { this.customOpts = opts; } /** * 获取当前的自定义opts参数 * @returns {Object|null} 当前的自定义opts参数 */ getCustomOpts() { return this.customOpts; } /** * 清除自定义的opts参数,恢复默认行为 */ clearCustomOpts() { this.customOpts = null; } speak(text, customOpts = null) { text = this.preprocessText(text); // #ifdef H5 // H5端使用Web Speech API if ("speechSynthesis" in window) { const utterance = new SpeechSynthesisUtterance(text); utterance.lang = this.ttsParams.lang; utterance.rate = this.ttsParams.speed; utterance.pitch = this.ttsParams.pitch; utterance.volume = this.ttsParams.volume; speechSynthesis.speak(utterance); } // #endif // #ifdef APP-PLUS let opts; // 优先级:方法参数传入的customOpts > setCustomOpts设置的customOpts > 默认opts if (customOpts) { opts = customOpts; } else if (this.customOpts) { opts = this.customOpts; } else { // 使用默认的opts逻辑 opts = this.platform == "ios" ? { rate: this.ttsParams.speed, lang: "zh-CN", volume: 1, } : { pitch: this.ttsParams.pitch, speechRate: this.ttsParams.speed, queueMode: 1, }; } this.TTSModule.speak(text, opts, (e) => { console.log(e, "读取成功"); }); // #endif } stop() { if (this.TTSModule) { this.TTSModule.stop(); } } destroy() { // 停止当前的语音合成 this.stop(); // #ifdef H5 // H5端取消所有语音合成 if ("speechSynthesis" in window) { speechSynthesis.cancel(); } // #endif // 清理TTSModule引用 this.TTSModule = null; // 清理自定义opts this.customOpts = null; // 重置参数 this.ttsParams = { lang: "zh-CN", speed: 1, pitch: 1, volume: 1, }; } } export default VolumeTTS;