result.js 2.37 KB

import { convertDate } from '../../utils/util.js';
//获取应用实例
const app = getApp();
const type = app.globalData.getTypeList();

let audio = null;
let formateDate = function (audioList) {
    return audioList.map(audio => {
        return {
            ...audio,
            date: convertDate(audio.time)
        };
    }).reverse();
};

Page({
    data: {
        audioList: formateDate(app.globalData.getAudioList())
    },
    onLoad(options){
        this.setData({
            audioList: formateDate(app.globalData.getAudioList())
        });
    },
    onUnload(){
        this.resetAudio();
    },
    play(e){
        const { path } = e.target.dataset;
        const target = app.globalData.getAudioList().find(v => v.path === path);
        this.resetAudio();
        audio = wx.createInnerAudioContext({useWebAudioImplement: true});
        audio.autoplay = true;
        audio.src = target.path;
        // 播放失败要移除缓存内容
        audio.onError(err => {
            wx.showModal({
                title: '提示',
                content: '该语音缓存失效,点击确定删除',
                success: res => {
                    if(!res.confirm){
                        return;
                    }
                    const newList = app.globalData.setAudioList('delete', target.path);
                    this.setData({
                        audioList: formateDate(newList)
                    });
                }
            });
        });
    },
    download(e){
        const { path } = e.target.dataset;
        const target = app.globalData.getAudioList().find(v => v.path === path);
        const ext = target.path.split('.').pop();
        wx.shareFileMessage({
            filePath: target.path,
            fileName: `${target.text.slice(0, 8)}.${ext}`
        });
    },
    delete(e){
        const { path } = e.target.dataset;
        wx.showModal({
            title: '提示',
            content: '确认删除吗?',
            success: res => {
                if(!res.confirm){
                    return;
                }
                const newList = app.globalData.setAudioList('delete', path);
                this.setData({
                    audioList: formateDate(newList)
                });
            }
        });
    },
    resetAudio(){
        if(audio){
            audio.destroy();
            audio = null;
        }
    }
});