class VolumeTTS { ttsParams = { lang: "zh-CN", speed: 1, // 将 0-10 转换为 0-1 pitch: 1, // 将 0-10 转换为 0-1 volume: 1, }; TTSModule; 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(""); }); } speak(text) { 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 = 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; // 重置参数 this.ttsParams = { lang: "zh-CN", speed: 1, pitch: 1, volume: 1, }; } } export default VolumeTTS;