AudioTts.js
14.5 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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
// components/tab-input/index.js
const {
ALIYUN,
bytedanceConfig
} = require("~/config")
const getToken = require("~/utils/aliyun/token").getToken
const SpeechSynthesizer = require("~/utils/aliyun/tts")
const sleep = require("~/utils/aliyun/util").sleep
const formatTime = require("~/utils/aliyun/util").formatTime
const fs = wx.getFileSystemManager()
import getSignature from '../../upload/signature'
import uploadFile from '../../upload/uploadFile'
import aiApi from "../../../../aiApi";
import {
speechEmoji,
soundEmoji,
definitionEmoji,
toneWords,
SpeechRateValue,
calculateStars,
calculateEmotion,
calculateIntonation
} from '../../contant'
let timer = null
Component({
/**
* 组件的属性列表
*/
properties: {
avatar: String,
voice: String,
roleName: String,
objection_id:String,
isDemo: {
value: false,
type: Boolean,
},
showSpeechPopup: {
type: Boolean,
observer: function (n) {
if (n) {
timer = setInterval(() => {
this.stopAudio()
}, 300)
this.stopAudio()
const {
list
} = this.data;
this.setData({
list
})
} else {
clearInterval(timer)
}
}
}
},
/**
* 组件的初始数据
*/
data: {
status: 'end',
list: [],
audioIndex: '',
ttsStart: false,
ttsText: "是的发生大客户"
},
lifetimes: {
attached() {
this.connectSr()
this.getOssSignature()
this.getVoiceConfig()
},
detached() {
this.stopAudio()
}
},
/**
* 组件的方法列表
*/
methods: {
//获取火山复刻配置
getVoiceConfig() {
aiApi
.getVoiceConfig({
person_type: this.data.roleName.replace(/客户/, '')
}).then(res => {
this.setData({
voiceInfo: res
})
})
},
HS_play(text) {
const {
uuid
} = wx.$util.getUserInfo();
const {
access_token,
app_id: appid,
voice_id: voice_type
} = this.data.voiceInfo;
const _this = this;
const cluster = "volcano_mega";
wx.request({
url: bytedanceConfig.url,
method: 'post',
data: {
app: {
appid,
token: access_token,
cluster,
voice_type,
},
user: {
uid: uuid
},
"audio": {
"voice_type": voice_type,
"encoding": "mp3",
"speed_ratio": 1.0,
"volume_ratio": 1.0,
"pitch_ratio": 1.0,
},
"request": {
"reqid": uuid + Date.now(),
"text": text,
"text_type": "plain",
"operation": "query",
"with_frontend": 1,
"frontend_type": "unitTson"
}
},
header: {
"Authorization": `Bearer;${access_token}`
},
success(response) {
const arrayBuffer = response.data.data
const audioPath = wx.env.USER_DATA_PATH + `/${Date.now()}.mp3`
const fs = wx.getFileSystemManager();
fs.writeFile({
filePath: audioPath,
data: arrayBuffer,
encoding: 'base64',
success(res) {
_this.setAudio(_this.data.selectIndex, audioPath, 'ai')
// const audioContext = wx.createInnerAudioContext();
// audioContext.src = audioPath;
// audioContext.play();
},
})
}
})
},
getOssSignature() {
getSignature().then(res => {
this.data.ossOption = res
})
},
async connectSr(options) {
try {
this.data.token = await getToken(ALIYUN.AKID,
ALIYUN.AKKEY)
} catch (e) {
console.log("error on get token:", JSON.stringify(e))
return
}
let tts = new SpeechSynthesizer({
url: ALIYUN.URL,
appkey: ALIYUN.APPKEY,
token: this.data.token
})
tts.on("meta", (msg) => {
console.log("Client recv metainfo:", msg)
})
tts.on("data", (msg) => {
console.log(`recv size: ${msg.byteLength}`)
//console.log(dumpFile.write(msg, "binary"))
if (this.data.saveFile) {
try {
fs.appendFileSync(
this.data.saveFile,
msg,
"binary"
)
console.log(`append ${msg.byteLength}`)
} catch (e) {
console.error(e)
}
} else {
console.log("save file empty")
}
})
tts.on("completed", async (msg) => {
console.log("Client recv completed:", msg)
await sleep(100)
fs.close({
fd: this.data.saveFd,
success: (res) => {
this.setAudio(this.data.selectIndex, this.data.saveFile, 'ai')
// this.data.ctx.onEnded((res) => {
// const {
// list,
// selectIndex
// } = this.data;
// if (list[selectIndex]) {
// list[selectIndex].openAudio = false;
// this.setData({
// list
// })
// }
// fs.unlink({
// filePath: this.data.saveFile,
// success: (res) => {
// console.log(`remove ${this.data.saveFile} done`)
// this.data.saveFile = null
// this.data.saveFd = null
// },
// failed: (res) => {
// console.log("remove failed:" + res.errMsg)
// }
// })
// })
},
fail: (res) => {
console.log("saved file error:" + res.errMsg)
}
})
})
tts.on("closed", () => {
console.log("Client recv closed")
})
tts.on("failed", (msg) => {
console.log("Client recv failed:", msg)
})
this.data.tts = tts
},
toBottom() {
const pages = getCurrentPages()
const curPage = pages[pages.length - 1];
if(curPage) curPage.toBottom()
},
setAudio(index, filePath, type) {
if (!this.data['ctx_' + index])
this.data['ctx_' + index] = wx.createInnerAudioContext()
const {
list,
audioIndex,
status
} = this.data;
if (type) {
const idx = list.findIndex(i => i.id == index)
list[idx].filePath = filePath;
this.setData({
list
})
this.toBottom()
}
console.log(index, audioIndex, status, filePath)
this.data['ctx_' + index].src = filePath; // 替换为你的音频文件路径
// 监听播放完成事件
const _this = this;
this.data['ctx_' + index].onEnded(() => {
_this.setData({
status: 'ending'
})
console.log('结束...')
});
this.data['ctx_' + index].onPause(() => {
this.setData({
status: 'pause'
})
console.log('暂停...')
})
if (index === audioIndex && status == 'start') {
this.data['ctx_' + index].pause()
return
}
if (index === audioIndex && status == 'pause') {
this.data['ctx_' + index].play()
return
}
this.stopAudio()
this.setData({
audioIndex: index
})
this.data['ctx_' + index].play();
// 开始播放音频
this.data['ctx_' + index].onPlay(() => {
this.setData({
status: 'start'
})
console.log('开始...')
})
},
//结束播放
stopAudio() {
const {
audioIndex
} = this.data
if (this.data['ctx_' + audioIndex])
this.data['ctx_' + audioIndex].stop()
},
//自己声音播放
playVoice: wx.$util.throttle(function (e) {
const {
id,
file: filePath // 获取语音文件的路径或URL
} = e.currentTarget.dataset
this.setAudio(id, filePath)
}, 1000),
//isPlay有值代表攻防话术,并打开播放
addList(val, isPlay) {
val.id = new Date().getTime()
let {
list
} = this.data;
list.forEach(i => {
if (i.role == 2) {
i.isReset = false
}
})
if (val.role == 2) {
val.isReset = true
this.getVoice(val, list.length)
}
if (isPlay) {
val.isOpenDefense = true //开启攻防
}
list = [...list, val]
this.setData({
list
}, () => {
this.toBottom()
})
if (val.role == 2) {
this.setData({
resetIndex: list.length - 1
})
}
},
async getVoice(val, i) {
const url = await uploadFile(val.filePath, this.data.ossOption)
aiApi.getVoice({
file_link: url
}).then(res => {
const Sentences = res.Sentences
const {
resetIndex
} = this.data;
if (resetIndex < i) {
return
}
const {
speed,
intonation,
definition,
redundant
} = this.getSentencesDetail(Sentences, this.data.list[i].content) || {}
this.setData({
['list[' + i + '].voiceUrl']: url,
['list[' + i + '].Sentences']: Sentences,
['list[' + i + '].speed']: speed,
['list[' + i + '].intonation']: intonation,
['list[' + i + '].definition']: definition,
['list[' + i + '].redundant']: redundant
});
})
},
getSentencesDetail(Sentences, redundantWords) {
if (Sentences.length == 0)
return
let totalSpeed = 0;
let totalEmotionValue = 0;
let SpeechRateAll = []
Sentences.forEach(i => {
totalSpeed += i.SpeechRate;
totalEmotionValue += i.EmotionValue;
SpeechRateAll.push(i.EmotionValue)
})
const averageSpeed = totalSpeed / Sentences.length;
const averageEmotionValue = totalEmotionValue / Sentences.length
const speed = SpeechRateValue[calculateStars(averageSpeed)]
const intonation = calculateIntonation(SpeechRateAll)
const definition = calculateEmotion(averageEmotionValue)
const redundant = this.getNum(redundantWords)
return {
speed,
intonation,
definition,
redundant
}
},
getNum(words) {
// 使用reduce来累加每个音调词在字符串中出现的次数
const wordNum = toneWords.reduce((count, toneWord) => {
// 使用正则表达式匹配音调词,并计算匹配到的次数
const matches = words.match(new RegExp(toneWord, "g"));
// 如果匹配到结果,则累加,否则保持当前计数
return count + (matches ? matches.length - 1 : 0);
}, 0); // 初始计数为0
return wordNum > 0 ? wordNum : '无'
},
getList(step, defenseIndex) {
let {
list,
} = this.data;
let history = '';
if (step == 'defense') {
list = list.slice(defenseIndex)
}
list.forEach(item => {
if (item.role == 1) {
history += `客户说:${item.content}`
} else {
history += `销售说:${item.content}`
}
})
return history
},
//重置
resetChat() {
let {
list,
resetIndex
} = this.data;
if (!list[list.length - 1].content) {
wx.$util.showToast('AI还未回复')
return
}
list = list.slice(0, resetIndex);
let idx = list.length - 2;
list.forEach((item, k) => {
if (item.role == 2) {
idx = k
}
})
this.setData({
list,
resetIndex: idx
})
this.toBottom()
this.stopAudio()
},
setSuggest(val, i) {
const {
resetIndex
} = this.data;
if (resetIndex < i) {
return
}
this.setData({
['list[' + i + ']']: {
...this.data.list[i],
...val
}
})
},
/**
* @param index 1代表结束了,不播放音频
*/
setList(val, index) {
const {
list
} = this.data;
let len = list.length - 1;
if (index == -1) {
len = len - 1
}
list[len] = {
...list[len],
...val
}
this.setData({
list
}, () => {
this.toBottom()
})
console.log(list, len)
if (!index) this.playAudio(list[len].id)
},
handleHidden(e) {
const {
index
} = e.currentTarget.dataset
const {
list
} = this.data;
list[index].show = false;
this.setData({
list
})
},
handleShow(e) {
const {
index
} = e.currentTarget.dataset
const {
list
} = this.data;
list[index].show = true;
this.setData({
list
})
},
//AI声音播放
playAudio: wx.$util.throttle(function (e) {
let index = e.currentTarget ? e.currentTarget.dataset.index : e
const {
isDemo
} = this.data
isDemo ? this.playTTS(index) : this.onTtsStart(index)
}, 1000),
//火山声音复刻
playTTS(index) {
const {
list,
} = this.data;
this.stopAudio()
this.setData({
selectIndex: index
})
const idx = list.findIndex(i => i.id == index)
this.HS_play(list[idx].content)
},
async onTtsStart(index) {
const {
list,
} = this.data;
this.stopAudio()
this.setData({
selectIndex: index
})
this.data.ttsStart = true;
let save = formatTime(new Date()) + ".wav"
let savePath = wx.env.USER_DATA_PATH + "/" + save
console.log(`save to ${savePath}`)
fs.open({
filePath: savePath,
flag: "a+",
success: async (res) => {
console.log(`open ${savePath} done`)
this.data.saveFd = res.fd
this.data.saveFile = savePath
let param = this.data.tts.defaultStartParams()
const idx = list.findIndex(i => i.id == index)
param.text = list[idx].content;
param.voice = this.data.voice
try {
await this.data.tts.start(param)
this.setData({
list,
audioIndex: idx
})
console.log("tts done")
this.data.ttsStart = false
} catch (e) {
console.log("tts start error:" + e)
}
},
fail: (res) => {
console.log(`open ${savePath} failed: ${res.errMsg}`)
}
})
},
}
})