微信小程序使用同声传译插件实现文本转语音播放(适用于食堂取餐报餐场景)

一、微信小程序后台启用插件

在这里插入图片描述

二、微信小程序配置文件

在项目app.json中添加以下内容

"plugins": {
    "WechatSI": {
        "version": "0.3.5",
        "provider": "wx069ba97219f66d99"
    }
}

三、小程序页面调用插件播放语音

在需要播放语音的页面添加相关的代码,为提升播放效率,相关的播放内容将缓存起来,已播放过的内容直接调用缓存直接播放,否则从网络中请求新的语音数据。

//引入插件:微信同声传译
const plugin = requirePlugin('WechatSI');
//获取全局唯一的语音识别管理器recordRecoManager
const manager = plugin.getRecordRecognitionManager();

onLoad: function(options) {
    //创建内部 audio 上下文 InnerAudioContext 对象。
    this.innerAudioContext = wx.createInnerAudioContext();
    this.innerAudioContext.onError(function (res) {
        console.log(res);
        wx.showToast({
            title: '语音播放失败',
            icon: 'none',
        })
    })
    this.wordYun("查无订餐记录", function() {
        that.setData({
            loadingFlag: !1
        })
    })
},

// 文字转语音
wordYun: function(e, cb) {
    var that = this;
    var content = e;

    var t_file = wx.getStorageSync(e)
    console.log(t_file)
    if (t_file) {
        console.log("文件播放")
        that.innerAudioContext.src = t_file
        that.innerAudioContext.play(); //播放音频
    } else {
        console.log("网络播放")
        plugin.textToSpeech({
            lang: "zh_CN",
            tts: true,
            content: content,
            success: function(res) {
                console.log(res);
                console.log("succ tts", res.filename);
                that.setData({
                    src: res.filename
                })

                wx.downloadFile({
                    url: res.filename,
                    success: function(res) {
                        let path = res.tempFilePath
                        console.log("my path")
                        console.log(path)
                        that.innerAudioContext.src = path
                        that.innerAudioContext.play(); //播放音频

                        wx.setStorage({
                            key: e,
                            data: path,
                        })
                        // wx.saveFile({
                        //     tempFilePath: path,
                        //     success(res) {
                        //         var savedFilePath = res.savedFilePath;



                        //     },
                        // }
                    }
                })
                // that.innerAudioContext.src = res.filename
                // that.innerAudioContext.play(); //播放音频
                typeof cb == "function" && cb()

            },
            fail: function(res) {
                console.log("fail tts", res)
            }
        })
    }
},
  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值