index.js 2.14 KB
//index.js
//获取应用实例
const app = getApp();
const selectedIndex = app.globalData.getSelectedTypeIndex();
const type = app.globalData.getTypeList();

let audio = null;

Page({
    data: {
        placeholder: '点击此处输入文字',
        text: '',
        type,
        selectedIndex: String(selectedIndex) ? selectedIndex : 5
    },
    onLoad(){
        wx.showShareMenu();
    },
    inputText(e){
        this.data.text = e.detail.value;
    },
    play(){
        const text = this.data.text || this.data.placeholder;
        const url = this.data.type[this.data.selectedIndex].createUrl(text);
        this.resetAudio();
        audio = wx.createInnerAudioContext({useWebAudioImplement: true});
        audio.autoplay = true;
        // 检查是否播放过  
        const audioList = app.globalData.getAudioList();
        const playedIndex = audioList.findIndex(v => v.url === url);
        // 播放过,使用本地文件减少请求  
        if(playedIndex > -1){
            return audio.src = audioList[playedIndex].path;
        }
        // 未播放过,先下载再播放  
        wx.downloadFile({
            url,
            success (res) {
                audio.src = res.tempFilePath;
                app.globalData.setAudioList('add', {
                    // 音频文本  
                    text,
                    // 音频网络地址  
                    url,
                    // 音频本地地址  
                    path: res.tempFilePath,
                    // 音频创建时间  
                    time: Date.now()
                });
            }
        });
    },
    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'
        });
    }
});