前言
-
需求:微信小程序如何实现提供指定的文本,然后采取语音播报?
-
环境:
"@tarojs/react": "3.5.12", "react": "^18.0.0"
实现
- 引入插件:微信同声传译
具体步骤
-
小程序申请插件
小程序控制台>账号设置>第三方设置>插件管理>添加插件 -
项目引入插件
-
进入项目
app.config.js(项目配置文件)export default defineAppConfig({ pages: [ //... ], subPackages: [ //... ], plugins: { WechatSI: { version: '0.3.6', provider: 'wx069ba97219f66d99' }, }, //... }) ⚠️注意:
version和provider对应文档配合设置 -
封装方法
const plugin = requirePlugin("WechatSI"); /** * @func 语音合成 * @desc api文档 * https://mp.weixin.qq.com/wxopen/plugindevdoc?appid=wx069ba97219f66d99&token=1441399898&lang=zh_CN */ function textToSpeech(args) { const mediaAudioPlayer = wx.createInnerAudioContext(); plugin.textToSpeech({ lang: "zh_CN", tts: true, success: ({ filename }) => { mediaAudioPlayer.autoplay = true; mediaAudioPlayer.src = filename; mediaAudioPlayer.play(); }, fail: (e) => { console.log("🚀 ~ file: index.jsx:18 ~ useEffect ~ e:", e); }, ...args, }) }args<object>:参数与文档中textToSpeech方法参数一至关键参数 描述 content 需要语音播报的文本
-
疑问
以下是本人对改内容的一些疑问?恳请读者能为我指点迷津,十分感谢🙏
Q:createInnerAudioContext的文档中有destroy方法,该如何在语音播放完后调用该方法?
-
尝试方法
//❌ 语音没播报出来就销毁了 function textToSpeech(args) { const mediaAudioPlayer = wx.createInnerAudioContext(); try{ plugin.textToSpeech({ //..., }) }finally{ mediaAudioPlayer.destroy(); } } //❌ 不存在.then方法 function textToSpeech(args) { const mediaAudioPlayer = wx.createInnerAudioContext(); plugin.textToSpeech({ //..., }).then(()=>{ mediaAudioPlayer.destroy(); }) } // 万一语音时长超过1秒,是否会被提前销毁 function textToSpeech(args) { const mediaAudioPlayer = wx.createInnerAudioContext(); plugin.textToSpeech({ //..., }) setTimeout(()=>{ mediaAudioPlayer.destroy(); },1000) }
Q:若不调用destroy方法会产生内存泄露不?