index.js 2.53 KB
//index.js
//获取应用实例
const app = getApp();
const storageKey = 'audioTypeselectedIndex';
const selectedIndex = wx.getStorageSync(storageKey);
const type = [
    {
        desc: '男声一',
        createUrl(text){
            return `https://fanyi.sogou.com/reventondc/synthesis?text=${text}&speed=1&lang=zh-CHS&from=translateweb&speaker=1`
        }
    },
    {
        desc: '男声二',
        createUrl(text){
            return `https://fanyi.sogou.com/reventondc/synthesis?text=${text}&speed=1&lang=zh-CHS&from=translateweb&speaker=4`
        }
    },
    {
        desc: '女声一',
        createUrl(text){
            return `https://fanyi.sogou.com/reventondc/synthesis?text=${text}&speed=1&lang=zh-CHS&from=translateweb&speaker=2`
        }
    },
    {
        desc: '女声二',
        createUrl(text){
            return `https://fanyi.sogou.com/reventondc/synthesis?text=${text}&speed=1&lang=zh-CHS&from=translateweb&speaker=3`
        }
    },
    {
        desc: '女声三',
        createUrl(text){
            return `https://fanyi.sogou.com/reventondc/synthesis?text=${text}&speed=1&lang=zh-CHS&from=translateweb&speaker=5`
        }
    },
    {
        desc: '女声四',
        createUrl(text){
            return `https://fanyi.sogou.com/reventondc/synthesis?text=${text}&speed=1&lang=zh-CHS&from=translateweb&speaker=6`
        }
    },
    {
        desc: '女声五',
        createUrl(text){
            return `https://tts.youdao.com/fanyivoice?word=${text}&le=zh&keyfrom=speaker-target`
        }
    }
];

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;
        this.resetAudio();
        audio = wx.createInnerAudioContext({useWebAudioImplement: true});
        audio.autoplay = true;
        audio.src = this.data.type[this.data.selectedIndex].createUrl(text);
    },
    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();
        });
        wx.setStorageSync(storageKey, index);
    }
});