-
Notifications
You must be signed in to change notification settings - Fork 31
/
live2d_test.html
589 lines (386 loc) · 13.9 KB
/
live2d_test.html
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
579
580
581
582
583
584
585
586
587
588
589
<html>
<head>
<script src="./js/live2dcubismcore.min.js"></script>
<script src="./js/live2d.min.js"></script>
<script src="./js/pixi.min.js"></script>
<!-- if only Cubism 4 support-->
<script src="./js/cubism4.min.js"></script>
<script src="./js/jquery-3.1.1.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<canvas id="canvas" ></canvas>
<div id="control">
<button id="play">测试音频</button> <button onclick="JavaScript:window.location.href='/'">返回菜单</button>
<br />
<label>数字人模型</label>
<select id="model_list"></select> <button id="update_model">更新模型</button>
<br />
<label>眼神跟随鼠标</label>
<input type="radio" name="eyes" value="true" checked >
<label>跟随鼠标</label><input type="radio" id="option2" name="eyes" value="false" ><label >前方直视</label>
<br />
<label>背景控制</label>
<input type="radio" id="option1" name="options" value="bg_color" checked >
<label for="option1">背景颜色</label><input id="bg_color" type="text" style="width:100px;" ><br /><input type="radio" id="option2" name="options" value="bg_img" ><label for="option2">背景图片</label> <input type="file" id="imgupload" style="display:none"/>
<button id="openImgUpload">上传图片</button> <button id="update_bg">更新背景</button>
<br />
<label>语音接口地址</label>
<input type="search" id="apiurl" style="width:200px;" value="http://127.0.0.1:9880" >
<br />
<label>推理文本语言种类</label>
<input type="search" id="text_lang" style="width:200px;" value="zh" >
<br />
<label>参考音频</label>
<input type="search" id="ref_audio_path" style="width:200px;" value="./Keira.wav" >
<br />
<label>参考音频文本</label>
<input type="search" id="prompt_text" style="width:300px;" value="光动嘴不如亲自做给你看,等我一下呀" >
<br />
<label>参考音频文本语种</label>
<input type="search" id="prompt_lang" style="width:200px;" value="zh" >
<br />
<label>切分方式</label>
<input type="search" id="text_split_method" style="width:200px;" value="cut5" >
<br />
<label>语速</label>
<input type="search" id="speed_factor" style="width:200px;" value="1.0" >
<br />
<br />
<textarea id="text" style="width:400px;height:300px;">神经网络是通过假设的因素去“猜”稀疏矩阵的空缺数据,猜出来之后,再通过反向传播的逆运算来反推稀疏矩阵已存在的数据是否正确,从而判断“猜”出来的数据是否正确。这就是用来做数据预测的矩阵分解算法:通俗地讲,跟算命差不多,但是基于数学原理,如果通过反推证明针对一个人的算命策略都是对的,那么就把这套流程应用到其他人身上。</textarea>
<br /><br />
<button id="start">并行推理</button> <button id="start_stream">流式推理</button> <button id="stop">停止讲话</button>
</div>
<script type="text/javascript">
$('input[name="eyes"]').click(function(){
var radioValue = $("input[name='eyes']:checked").val();
setCookie("eyes", radioValue, 1024);
location.reload();
});
$('#openImgUpload').click(function(){
$('#imgupload').trigger('click');
});
$('#imgupload').on('change', function(){
var formData = new FormData();
formData.append('image', $(this)[0].files[0]);
$.ajax({
url: '/upload',
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function(data){
console.log('上传成功: ');
console.log(data.filename);
setCookie("bg_img", data.filename, 1024);
var radioValue = $("input[name='options']:checked").val();
setCookie("bg_con", radioValue, 1024);
location.reload();
}
});
});
// 从 cookie 中获取保存的值
function getCookie(name) {
const value = "; " + document.cookie;
const parts = value.split("; " + name + "=");
if (parts.length === 2) return parts.pop().split(";").shift();
}
// 将选中的值写入 cookie
function setCookie(name, value, days) {
const date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
const expires = "expires=" + date.toUTCString();
document.cookie = name + "=" + value + ";" + expires + ";path=/";
}
// 控制背景色
// 读取 cookie 中的值并设置单选按钮的选中状态
const selectedValue = getCookie("bg_con");
if (selectedValue) {
const radioButtons = document.getElementsByName("options");
radioButtons.forEach(radio => {
radio.checked = false;
if (radio.value === selectedValue) {
radio.checked = true;
}
});
}
// 读取 cookie 中的值并设置单选按钮的选中状态
const eyesValue = getCookie("eyes");
if (eyesValue) {
const radioButtons = document.getElementsByName("eyes");
radioButtons.forEach(radio => {
radio.checked = false;
if (radio.value == eyesValue) {
radio.checked = true;
}
});
}
// 设置背景色
let radioValue = $("input[name='options']:checked").val();
if (getCookie("bg_color") === undefined) {$("#bg_color").val("gray");}else{$("#bg_color").val(getCookie("bg_color"));}
if(radioValue == "bg_color"){
$("#canvas").css("background-color",$("#bg_color").val());
}else{
if (getCookie("bg_img") === undefined) {
}else{
let imageUrl = "./uploads/"+getCookie("bg_img");
$("#canvas").css("background-image", "url(" + imageUrl + ")");
// $("#canvas").css("background-repeat","space");
}
}
let eye_bool = true;
if (getCookie("eyes") === undefined) {}else{
if (getCookie("eyes")=="false"){
eye_bool = false;
}
}
// 数字人模型
var cubism4Model = './models/<%=model_path%>/<%=model_path%>.model3.json';
var selected_model = '<%-model_path%>';
var model_list = '<%-model_list%>';
model_list = JSON.parse(model_list);
var $select = $("#model_list");
$select.empty(); // 清空旧选项
// 遍历新选项列表并添加到select元素中
$.each(model_list, function(index, value) {
if (value==selected_model){
$select.append($("<option selected></option>").attr("value", value).text(value));
}else{
$select.append($("<option></option>").attr("value", value).text(value));
}
});
// const cubism4Model = "./Hiyori/Hiyori.model3.json";
// const cubism4Model = "./March 7th/March 7th.model3.json";
const live2d = PIXI.live2d;
(async function main() {
const app = new PIXI.Application({
view: document.getElementById("canvas"),
autoStart: true,
resizeTo: window,
// 背景是否透明
transparent: true,
backgroundAlpha: 0,
// autoDensity:true,
// autoResize: true,
antialias: true,
});
var models = await Promise.all([
live2d.Live2DModel.from(cubism4Model,{ autoInteract: eye_bool })
]);
models.forEach((model) => {
app.stage.addChild(model);
const scaleX = (innerWidth ) / model.width;
const scaleY = (innerHeight ) / model.height;
// fit the window
model.scale.set(Math.min(scaleX, scaleY));
model.y = innerHeight * 0.1;
draggable(model);
// addFrame(model);
// addHitAreaFrames(model);
// talk(model)
});
const model4 = models[0];
model4.x = innerWidth / 2;
model4.on("hit", (hitAreas) => {
if (hitAreas.includes("Body")) {
model4.motion("Tap");
}
if (hitAreas.includes("Head")) {
model4.expression();
}
});
// 更新背景
$("#update_bg").click(function() {
var radioValue = $("input[name='options']:checked").val();
setCookie("bg_con", radioValue, 1024);
setCookie("bg_color", $("#bg_color").val(), 1024);
location.reload();
});
// 更新模型
$("#update_model").click(function() {
axios.get('/edit_config',{
params: {"model_path":$("#model_list").val()}
})
.then(response => {
// 处理成功响应
console.log(response.data);
location.reload();
})
.catch(error => {
// 处理错误
console.error(error);
alert(error);
});
});
$("#play").click(function() {
talk(model4,"./Keira.wav");
});
$("#stop").click(function() {
model4.stopSpeaking();
});
$("#start").click(function() {
console.log($("#text").val());
let text = $("#text").val().trim();
if(text == ""){
alert("请输入推理内容");
return false;
}
$("#start").prop("disabled", true);
axios.defaults.timeout = 300000;
axios.post($("#apiurl").val(), {
text_lang: $("#text_lang").val(),
ref_audio_path: $("#ref_audio_path").val(),
prompt_lang: $("#prompt_lang").val(),
prompt_text: $("#prompt_text").val(),
text_split_method: $("#text_split_method").val(),
batch_size: 10,
media_type: 'wav',
speed_factor: $("#speed_factor").val(),
text: $("#text").val()
}, {
responseType: 'arraybuffer'
})
.then(response => {
console.log(response.data);
// 将返回的音频数据转换为Blob对象
const audioBlob = new Blob([response.data], { type: 'audio/wav' });
console.log(audioBlob);
// 创建一个URL对象用于播放音频
const audioUrl = URL.createObjectURL(audioBlob);
// 创建一个新的Audio对象并播放音频
// const audio = new Audio(audioUrl);
//audio.play();
talk(model4,audioUrl);
$("#start").prop("disabled",false);
})
.catch(error => {
console.error('请求接口失败:', error);
$("#start").prop("disabled",false);
});
});
$("#start_stream").click(async function() {
console.log($("#text").val());
let text = $("#text").val().trim();
if(text == ""){
alert("请输入推理内容");
return false;
}
$("#start_stream").prop("disabled", true);
data = {text_lang: $("#text_lang").val(),
ref_audio_path: $("#ref_audio_path").val(),
prompt_lang: $("#prompt_lang").val(),
prompt_text: $("#prompt_text").val(),
text_split_method: $("#text_split_method").val(),
batch_size: 1,
media_type: 'ogg',
speed_factor: $("#speed_factor").val(),
text: $("#text").val(),
streaming_mode:"true"}
const response = await fetch($("#apiurl").val(), {
method: "POST",
body: JSON.stringify(data),
headers: {
"Content-Type": "application/json"
},
});
const reader = response.body.getReader();
const context = new (window.AudioContext || window.webkitAudioContext)();
const chunks = [];
while (true) {
const { done, value } = await reader.read();
if (done) {
console.log("***********************done");
$("#start_stream").prop("disabled", false);
break;
}
console.log("--------------------value");
console.log(value);
// 将返回的音频数据转换为Blob对象
const audioBlob = new Blob([value.buffer], { type: 'audio/ogg' });
// 创建一个URL对象用于播放音频
const audioUrl = URL.createObjectURL(audioBlob);
talk(model4,audioUrl);
// 将读取到的值添加到数组中
//chunks.push(value);
}
// // 合并所有读取到的二进制数据
// const audioBuffer = new Uint8Array(chunks.reduce((acc, val) => acc.concat(Array.from(val)), []));
// // 解码音频数据并播放
// context.decodeAudioData(audioBuffer.buffer).then(decodedData => {
// const source = context.createBufferSource();
// source.buffer = decodedData;
// source.connect(context.destination);
// source.start(0);
// }).catch(error => {
// console.error("Error decoding audio data:", error);
// });
});
})();
function talk(model,audio){
var audio_link = audio; //[Optional arg, can be null or empty] [relative or full url path] [mp3 or wav file] "./Keira.wav"
var volume = 1; // [Optional arg, can be null or empty] [0.0 - 1.0]
var expression = 8; // [Optional arg, can be null or empty] [index|name of expression]
var resetExpression = true; // [Optional arg, can be null or empty] [true|false] [default: true] [if true, expression will be reset to default after animation is over]
var crossOrigin = "anonymous"; // [Optional arg, to use not same-origin audios] [DEFAULT: null]
model.speak(audio_link, {volume: volume, expression:expression, resetExpression:resetExpression, crossOrigin: crossOrigin})
// Or if you want to keep some things default
model.speak(audio_link)
model.speak(audio_link, {volume: volume})
model.speak(audio_link, {expression:expression, resetExpression:resetExpression})
}
function draggable(model) {
model.buttonMode = true;
model.on("pointerdown", (e) => {
model.dragging = true;
model._pointerX = e.data.global.x - model.x;
model._pointerY = e.data.global.y - model.y;
});
model.on("pointermove", (e) => {
if (model.dragging) {
model.position.x = e.data.global.x - model._pointerX;
model.position.y = e.data.global.y - model._pointerY;
}
});
model.on("pointerupoutside", () => (model.dragging = false));
model.on("pointerup", () => (model.dragging = false));
}
function addFrame(model) {
const foreground = PIXI.Sprite.from(PIXI.Texture.WHITE);
foreground.width = model.internalModel.width;
foreground.height = model.internalModel.height;
foreground.alpha = 0.2;
model.addChild(foreground);
checkbox("Model Frames", (checked) => (foreground.visible = checked));
}
// function addHitAreaFrames(model) {
// const hitAreaFrames = new live2d.HitAreaFrames();
// hitAreaFrames.visible = true;
// model.addChild(hitAreaFrames);
// //checkbox("Hit Area Frames", (checked) => (hitAreaFrames.visible = checked));
// }
function checkbox(name, onChange) {
const id = name.replace(/\W/g, "").toLowerCase();
let checkbox = document.getElementById(id);
if (!checkbox) {
const p = document.createElement("p");
p.innerHTML = `<input type="checkbox" id="${id}"> <label for="${id}">${name}</label>`;
document.getElementById("control").appendChild(p);
checkbox = p.firstChild;
}
checkbox.addEventListener("change", () => {
onChange(checkbox.checked);
});
onChange(checkbox.checked);
}
</script>
<style>
#control{
position: absolute;
top:50px;
left: 50px;
color: white;
font-size:18px;
}
</style>
</body>
</html>