index.js
3.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
//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;
},
async play(){
const text = this.data.text || this.data.placeholder;
const url = this.data.type[this.data.selectedIndex].createUrl(text);
wx.showLoading({
title: '正在合成语音...',
mask: true
});
// 检查文本是否合规
const result = await new Promise((resolve, reject) => {
app.request({
url: `${app.globalData.domain}/open-api/wechat-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);
}
});
});
wx.hideLoading();
// 不合规结束
if(result.suggest !== 'pass'){
return wx.showToast({
title: '内容不合规',
icon: 'error',
mask: true,
duration: 2000
});
}
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'
});
}
});