index.js 4.54 KB
//index.js
//获取应用实例
const app = getApp();
const typeList = app.globalData.getTypeList();
const selectedIndex = typeList.length > 1 ? app.globalData.getSelectedTypeIndex() : 0;

let audio = null;

Page({
    data: {
        placeholder: '点击此处输入文字',
        text: '',
        typeList,
        selectedIndex: String(selectedIndex) ? selectedIndex : 0
    },
    onLoad(){
        wx.showShareMenu();
    },
    inputText(e){
        this.data.text = e.detail.value;
    },
    async play(){
        const text = this.data.text || this.data.placeholder;
        const selectedType = this.data.typeList[this.data.selectedIndex];
        const type = selectedType.desc;
        
        this.resetAudio();
        audio = wx.createInnerAudioContext({useWebAudioImplement: true});
        audio.autoplay = true;
        
        // 检查是否播放过  
        const audioList = app.globalData.getAudioList();
        let played = audioList.find(v => v.text === text && v.type === type);
        
        // 播放过,直接使用本地文件,无需检查合规性
        if(played){
            played.time = Date.now();
            app.globalData.setAudioList('delete', played.path);
            app.globalData.setAudioList('add', played);
            // 播放失败要移除缓存内容
            audio.onError(err => {
                app.globalData.setAudioList('delete', played.path);
                wx.showModal({
                    title: '提示',
                    content: '该语音播放过但缓存失效,点击确定重新播放',
                    showCancel: false,
                    success: res => {
                        this.play();
                    }
                });
            });
            return audio.src = played.path;
        }
        
        // 未播放过,先检查文本是否合规
        wx.showLoading({
            title: '正在合成语音...',
            mask: true
        });
        const result = await new Promise((resolve, reject) => {
            app.request({
                url: `${app.globalData.domain}/open-api/mp/msg-sec-check`,
                data: {
                    appid: 'wx330e54aa6000516d',
                    content: text,
                    openid: wx.getStorageSync('openid')
                },
                success(res){
                    resolve(JSON.parse(res.data?.data)?.result);
                },
                fail(err){
                    reject(err);
                }
            });
        });
        // 不合规结束
        if(result.suggest !== 'pass'){
            wx.hideLoading();
            return wx.showToast({
                title: '内容不合规',
                icon: 'error',
                mask: true,
                duration: 2000
            });
        }
        // 未播放过,调用TTS接口生成语音
        try {
            const url = await selectedType.createUrl(text);
            // 下载并播放
            wx.downloadFile({
                url,
                success (res) {
                    wx.hideLoading();
                    audio.src = res.tempFilePath;
                    app.globalData.setAudioList('add', {
                        // 音频文本  
                        text,
                        // 音频音效  
                        type,
                        // 音频网络地址  
                        url,
                        // 音频本地地址  
                        path: res.tempFilePath,
                        // 音频创建时间  
                        time: Date.now()
                    });
                },
                fail(err) {
                    console.log(err);
                    wx.hideLoading();
                    wx.showToast({
                        title: '下载失败',
                        icon: 'none'
                    });
                }
            });
        } catch (error) {
            wx.hideLoading();
            // TTS接口调用失败的错误已经在app.js中处理了
        }
    },
    clear(){
        this.resetAudio();
        this.setData({
            text: ''
        });
    },
    resetAudio(){
        if(audio){
            audio.destroy();
            audio = null;
        }
    },
    selectIndex(e){
        const { index } = e.target.dataset;
        this.setData({
            selectedIndex: index
        }, () => {
            this.play();
        });
        app.globalData.setSelectedTypeIndex(index);
    },
    gotoAudioList(){
        wx.navigateTo({
            url: '/pages/result/result'
        });
    }
});