ruiyun-human 1.0.2 → 1.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,898 @@
1
+ "use strict";
2
+ Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: "Module" } });
3
+ const vue = require("vue");
4
+ const _export_sfc = (sfc, props) => {
5
+ const target = sfc.__vccOpts || sfc;
6
+ for (const [key, val] of props) {
7
+ target[key] = val;
8
+ }
9
+ return target;
10
+ };
11
+ const _sfc_main$2 = {
12
+ __name: "index",
13
+ props: {
14
+ type: {
15
+ type: String,
16
+ default: "primary"
17
+ }
18
+ },
19
+ emits: ["click"],
20
+ setup(__props) {
21
+ return (_ctx, _cache) => {
22
+ return vue.openBlock(), vue.createElementBlock("button", {
23
+ class: vue.normalizeClass(["demo-btn", __props.type]),
24
+ onClick: _cache[0] || (_cache[0] = ($event) => _ctx.$emit("click"))
25
+ }, [
26
+ vue.renderSlot(_ctx.$slots, "default", {}, void 0, true)
27
+ ], 2);
28
+ };
29
+ }
30
+ };
31
+ const DemoButton = /* @__PURE__ */ _export_sfc(_sfc_main$2, [["__scopeId", "data-v-9a48516a"]]);
32
+ DemoButton.install = (app) => app.component("DemoButton", DemoButton);
33
+ const _hoisted_1 = { class: "demo-input-wrap" };
34
+ const _hoisted_2 = {
35
+ key: 0,
36
+ class: "prefix"
37
+ };
38
+ const _hoisted_3 = ["type", "placeholder", "value", "disabled"];
39
+ const _hoisted_4 = {
40
+ key: 1,
41
+ class: "suffix"
42
+ };
43
+ const _sfc_main$1 = {
44
+ __name: "index",
45
+ props: {
46
+ modelValue: {
47
+ type: [String, Number],
48
+ default: ""
49
+ },
50
+ placeholder: {
51
+ type: String,
52
+ default: "请输入内容"
53
+ },
54
+ inputType: {
55
+ type: String,
56
+ default: "text"
57
+ },
58
+ disabled: {
59
+ type: Boolean,
60
+ default: false
61
+ }
62
+ },
63
+ emits: ["update:modelValue", "focus", "blur"],
64
+ setup(__props, { emit: __emit }) {
65
+ const emit = __emit;
66
+ const handleInput = (e) => emit("update:modelValue", e.target.value);
67
+ return (_ctx, _cache) => {
68
+ return vue.openBlock(), vue.createElementBlock("div", _hoisted_1, [
69
+ _ctx.$slots.prefix ? (vue.openBlock(), vue.createElementBlock("span", _hoisted_2, [
70
+ vue.renderSlot(_ctx.$slots, "prefix", {}, void 0, true)
71
+ ])) : vue.createCommentVNode("", true),
72
+ vue.createElementVNode("input", {
73
+ class: "demo-input",
74
+ type: __props.inputType,
75
+ placeholder: __props.placeholder,
76
+ value: __props.modelValue,
77
+ disabled: __props.disabled,
78
+ onInput: handleInput,
79
+ onFocus: _cache[0] || (_cache[0] = ($event) => _ctx.$emit("focus")),
80
+ onBlur: _cache[1] || (_cache[1] = ($event) => _ctx.$emit("blur"))
81
+ }, null, 40, _hoisted_3),
82
+ _ctx.$slots.suffix ? (vue.openBlock(), vue.createElementBlock("span", _hoisted_4, [
83
+ vue.renderSlot(_ctx.$slots, "suffix", {}, void 0, true)
84
+ ])) : vue.createCommentVNode("", true)
85
+ ]);
86
+ };
87
+ }
88
+ };
89
+ const DemoInput = /* @__PURE__ */ _export_sfc(_sfc_main$1, [["__scopeId", "data-v-28a3493c"]]);
90
+ DemoInput.install = (app) => app.component("DemoInput", DemoInput);
91
+ var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
92
+ function getDefaultExportFromCjs(x) {
93
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
94
+ }
95
+ var recorder = { exports: {} };
96
+ /*!
97
+ *
98
+ * js-audio-recorder - js audio recorder plugin
99
+ *
100
+ * @version v1.0.7
101
+ * @homepage https://github.com/2fps/recorder
102
+ * @author 2fps <echoweb@126.com> (https://www.zhuyuntao.cn)
103
+ * @license MIT
104
+ *
105
+ */
106
+ (function(module2, exports2) {
107
+ !function(t, e) {
108
+ module2.exports = e();
109
+ }(commonjsGlobal, function() {
110
+ return function(t) {
111
+ var e = {};
112
+ function n(i) {
113
+ if (e[i]) return e[i].exports;
114
+ var o = e[i] = { i, l: false, exports: {} };
115
+ return t[i].call(o.exports, o, o.exports, n), o.l = true, o.exports;
116
+ }
117
+ return n.m = t, n.c = e, n.d = function(t2, e2, i) {
118
+ n.o(t2, e2) || Object.defineProperty(t2, e2, { enumerable: true, get: i });
119
+ }, n.r = function(t2) {
120
+ "undefined" != typeof Symbol && Symbol.toStringTag && Object.defineProperty(t2, Symbol.toStringTag, { value: "Module" }), Object.defineProperty(t2, "__esModule", { value: true });
121
+ }, n.t = function(t2, e2) {
122
+ if (1 & e2 && (t2 = n(t2)), 8 & e2) return t2;
123
+ if (4 & e2 && "object" == typeof t2 && t2 && t2.__esModule) return t2;
124
+ var i = /* @__PURE__ */ Object.create(null);
125
+ if (n.r(i), Object.defineProperty(i, "default", { enumerable: true, value: t2 }), 2 & e2 && "string" != typeof t2) for (var o in t2) n.d(i, o, (function(e3) {
126
+ return t2[e3];
127
+ }).bind(null, o));
128
+ return i;
129
+ }, n.n = function(t2) {
130
+ var e2 = t2 && t2.__esModule ? function() {
131
+ return t2.default;
132
+ } : function() {
133
+ return t2;
134
+ };
135
+ return n.d(e2, "a", e2), e2;
136
+ }, n.o = function(t2, e2) {
137
+ return Object.prototype.hasOwnProperty.call(t2, e2);
138
+ }, n.p = "", n(n.s = 1);
139
+ }([function(t, e, n) {
140
+ function i(t2, e2, n2) {
141
+ for (var i2 = 0; i2 < n2.length; i2++) t2.setUint8(e2 + i2, n2.charCodeAt(i2));
142
+ }
143
+ Object.defineProperty(e, "__esModule", { value: true }), e.compress = function(t2, e2, n2) {
144
+ for (var i2 = e2 / n2, o = Math.max(i2, 1), r = t2.left, a = t2.right, s = Math.floor((r.length + a.length) / i2), u = new Float32Array(s), c = 0, l = 0; c < s; ) {
145
+ var f = Math.floor(l);
146
+ u[c] = r[f], c++, a.length && (u[c] = a[f], c++), l += o;
147
+ }
148
+ return u;
149
+ }, e.encodePCM = function(t2, e2, n2) {
150
+ void 0 === n2 && (n2 = true);
151
+ var i2 = 0, o = t2.length * (e2 / 8), r = new ArrayBuffer(o), a = new DataView(r);
152
+ if (8 === e2) for (var s = 0; s < t2.length; s++, i2++) {
153
+ var u = (c = Math.max(-1, Math.min(1, t2[s]))) < 0 ? 128 * c : 127 * c;
154
+ u = +u + 128, a.setInt8(i2, u);
155
+ }
156
+ else for (s = 0; s < t2.length; s++, i2 += 2) {
157
+ var c = Math.max(-1, Math.min(1, t2[s]));
158
+ a.setInt16(i2, c < 0 ? 32768 * c : 32767 * c, n2);
159
+ }
160
+ return a;
161
+ }, e.encodeWAV = function(t2, e2, n2, o, r, a) {
162
+ void 0 === a && (a = true);
163
+ var s = n2 > e2 ? e2 : n2, u = r, c = new ArrayBuffer(44 + t2.byteLength), l = new DataView(c), f = o, p = 0;
164
+ i(l, p, "RIFF"), p += 4, l.setUint32(p, 36 + t2.byteLength, a), i(l, p += 4, "WAVE"), i(l, p += 4, "fmt "), p += 4, l.setUint32(p, 16, a), p += 4, l.setUint16(p, 1, a), p += 2, l.setUint16(p, f, a), p += 2, l.setUint32(p, s, a), p += 4, l.setUint32(p, f * s * (u / 8), a), p += 4, l.setUint16(p, f * (u / 8), a), p += 2, l.setUint16(p, u, a), i(l, p += 2, "data"), p += 4, l.setUint32(p, t2.byteLength, a), p += 4;
165
+ for (var d = 0; d < t2.byteLength; ) l.setUint8(p, t2.getUint8(d)), p++, d++;
166
+ return l;
167
+ };
168
+ }, function(t, e, n) {
169
+ var i, o = this && this.__extends || (i = function(t2, e2) {
170
+ return (i = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(t3, e3) {
171
+ t3.__proto__ = e3;
172
+ } || function(t3, e3) {
173
+ for (var n2 in e3) e3.hasOwnProperty(n2) && (t3[n2] = e3[n2]);
174
+ })(t2, e2);
175
+ }, function(t2, e2) {
176
+ function n2() {
177
+ this.constructor = t2;
178
+ }
179
+ i(t2, e2), t2.prototype = null === e2 ? Object.create(e2) : (n2.prototype = e2.prototype, new n2());
180
+ });
181
+ Object.defineProperty(e, "__esModule", { value: true });
182
+ var r = n(2), a = n(0), s = n(3), u = function(t2) {
183
+ function e2(e3) {
184
+ void 0 === e3 && (e3 = {});
185
+ var n2 = t2.call(this, e3) || this;
186
+ return n2.isrecording = false, n2.ispause = false, n2.isplaying = false, n2;
187
+ }
188
+ return o(e2, t2), e2.prototype.setOption = function(t3) {
189
+ void 0 === t3 && (t3 = {}), this.setNewOption(t3);
190
+ }, e2.prototype.start = function() {
191
+ return this.isrecording ? Promise.reject() : (this.isrecording = true, this.startRecord());
192
+ }, e2.prototype.pause = function() {
193
+ this.isrecording && !this.ispause && (this.ispause = true, this.pauseRecord());
194
+ }, e2.prototype.resume = function() {
195
+ this.isrecording && this.ispause && (this.ispause = false, this.resumeRecord());
196
+ }, e2.prototype.stop = function() {
197
+ this.isrecording && (this.isrecording = false, this.ispause = false, this.stopRecord());
198
+ }, e2.prototype.play = function() {
199
+ this.stop(), this.isplaying = true, this.onplay && this.onplay(), s.default.addPlayEnd(this.onplayend);
200
+ var t3 = this.getWAV();
201
+ t3.byteLength > 44 && s.default.play(t3.buffer);
202
+ }, e2.prototype.getPlayTime = function() {
203
+ return s.default.getPlayTime();
204
+ }, e2.prototype.pausePlay = function() {
205
+ !this.isrecording && this.isplaying && (this.isplaying = false, this.onpauseplay && this.onpauseplay(), s.default.pausePlay());
206
+ }, e2.prototype.resumePlay = function() {
207
+ this.isrecording || this.isplaying || (this.isplaying = true, this.onresumeplay && this.onresumeplay(), s.default.resumePlay());
208
+ }, e2.prototype.stopPlay = function() {
209
+ this.isrecording || (this.isplaying = false, this.onstopplay && this.onstopplay(), s.default.stopPlay());
210
+ }, e2.prototype.destroy = function() {
211
+ return s.default.destroyPlay(), this.destroyRecord();
212
+ }, e2.prototype.getRecordAnalyseData = function() {
213
+ return this.getAnalyseData();
214
+ }, e2.prototype.getPlayAnalyseData = function() {
215
+ return s.default.getAnalyseData();
216
+ }, e2.prototype.getPCM = function() {
217
+ this.stop();
218
+ var t3 = this.getData();
219
+ return t3 = a.compress(t3, this.inputSampleRate, this.outputSampleRate), a.encodePCM(t3, this.oututSampleBits, this.littleEdian);
220
+ }, e2.prototype.getPCMBlob = function() {
221
+ return new Blob([this.getPCM()]);
222
+ }, e2.prototype.downloadPCM = function(t3) {
223
+ void 0 === t3 && (t3 = "recorder");
224
+ var e3 = this.getPCMBlob();
225
+ r.downloadPCM(e3, t3);
226
+ }, e2.prototype.getWAV = function() {
227
+ var t3 = this.getPCM();
228
+ return a.encodeWAV(t3, this.inputSampleRate, this.outputSampleRate, this.config.numChannels, this.oututSampleBits, this.littleEdian);
229
+ }, e2.prototype.getWAVBlob = function() {
230
+ return new Blob([this.getWAV()], { type: "audio/wav" });
231
+ }, e2.prototype.downloadWAV = function(t3) {
232
+ void 0 === t3 && (t3 = "recorder");
233
+ var e3 = this.getWAVBlob();
234
+ r.downloadWAV(e3, t3);
235
+ }, e2.prototype.download = function(t3, e3, n2) {
236
+ r.download(t3, e3, n2);
237
+ }, e2.prototype.getChannelData = function() {
238
+ var t3 = this.getPCM(), e3 = t3.byteLength, n2 = this.littleEdian, i2 = { left: null, right: null };
239
+ if (2 === this.config.numChannels) {
240
+ var o2 = new DataView(new ArrayBuffer(e3 / 2)), r2 = new DataView(new ArrayBuffer(e3 / 2));
241
+ if (16 === this.config.sampleBits) for (var a2 = 0; a2 < e3 / 2; a2 += 2) o2.setInt16(a2, t3.getInt16(2 * a2, n2), n2), r2.setInt16(a2, t3.getInt16(2 * a2 + 2, n2), n2);
242
+ else for (a2 = 0; a2 < e3 / 2; a2 += 2) o2.setInt8(a2, t3.getInt8(2 * a2)), r2.setInt8(a2, t3.getInt8(2 * a2 + 1));
243
+ i2.left = o2, i2.right = r2;
244
+ } else i2.left = t3;
245
+ return i2;
246
+ }, e2;
247
+ }(n(5).default);
248
+ e.default = u;
249
+ }, function(t, e, n) {
250
+ function i(t2, e2, n2) {
251
+ var i2 = document.createElement("a");
252
+ i2.href = window.URL.createObjectURL(t2), i2.download = e2 + "." + n2, i2.click();
253
+ }
254
+ Object.defineProperty(e, "__esModule", { value: true }), e.downloadWAV = function(t2, e2) {
255
+ void 0 === e2 && (e2 = "recorder"), i(t2, e2, "wav");
256
+ }, e.downloadPCM = function(t2, e2) {
257
+ void 0 === e2 && (e2 = "recorder"), i(t2, e2, "pcm");
258
+ }, e.download = function(t2, e2, n2) {
259
+ return i(t2, e2, n2);
260
+ };
261
+ }, function(t, e, n) {
262
+ Object.defineProperty(e, "__esModule", { value: true });
263
+ var i = n(4), o = null, r = 0, a = 0, s = null, u = null, c = null, l = false, f = 0, p = function() {
264
+ };
265
+ function d() {
266
+ return l = false, s.decodeAudioData(c.slice(0), function(t2) {
267
+ (o = s.createBufferSource()).onended = function() {
268
+ l || (f = s.currentTime - a + r, p());
269
+ }, o.buffer = t2, o.connect(u), u.connect(s.destination), o.start(0, r), a = s.currentTime;
270
+ }, function(t2) {
271
+ i.throwError(t2);
272
+ });
273
+ }
274
+ function h() {
275
+ o && (o.stop(), o = null);
276
+ }
277
+ var y = function() {
278
+ function t2() {
279
+ }
280
+ return t2.play = function(t3) {
281
+ return s || (s = new (window.AudioContext || window.webkitAudioContext)(), (u = s.createAnalyser()).fftSize = 2048), this.stopPlay(), c = t3, f = 0, d();
282
+ }, t2.pausePlay = function() {
283
+ h(), r += s.currentTime - a, l = true;
284
+ }, t2.resumePlay = function() {
285
+ return d();
286
+ }, t2.stopPlay = function() {
287
+ r = 0, c = null, h();
288
+ }, t2.destroyPlay = function() {
289
+ this.stopPlay();
290
+ }, t2.getAnalyseData = function() {
291
+ var t3 = new Uint8Array(u.frequencyBinCount);
292
+ return u.getByteTimeDomainData(t3), t3;
293
+ }, t2.addPlayEnd = function(t3) {
294
+ void 0 === t3 && (t3 = function() {
295
+ }), p = t3;
296
+ }, t2.getPlayTime = function() {
297
+ var t3 = l ? r : s.currentTime - a + r;
298
+ return f || t3;
299
+ }, t2;
300
+ }();
301
+ e.default = y;
302
+ }, function(t, e, n) {
303
+ Object.defineProperty(e, "__esModule", { value: true }), e.throwError = function(t2) {
304
+ throw new Error(t2);
305
+ };
306
+ }, function(t, e, n) {
307
+ Object.defineProperty(e, "__esModule", { value: true });
308
+ var i = n(0), o = function() {
309
+ function t2(e2) {
310
+ void 0 === e2 && (e2 = {}), this.size = 0, this.lBuffer = [], this.rBuffer = [], this.tempPCM = [], this.inputSampleBits = 16, this.fileSize = 0, this.duration = 0, this.needRecord = true;
311
+ var n2, i2 = new (window.AudioContext || window.webkitAudioContext)();
312
+ this.inputSampleRate = i2.sampleRate, this.setNewOption(e2), this.littleEdian = (n2 = new ArrayBuffer(2), new DataView(n2).setInt16(0, 256, true), 256 === new Int16Array(n2)[0]), t2.initUserMedia();
313
+ }
314
+ return t2.prototype.setNewOption = function(t3) {
315
+ void 0 === t3 && (t3 = {}), this.config = { sampleBits: ~[8, 16].indexOf(t3.sampleBits) ? t3.sampleBits : 16, sampleRate: ~[8e3, 11025, 16e3, 22050, 24e3, 44100, 48e3].indexOf(t3.sampleRate) ? t3.sampleRate : this.inputSampleRate, numChannels: ~[1, 2].indexOf(t3.numChannels) ? t3.numChannels : 1 }, this.outputSampleRate = this.config.sampleRate, this.oututSampleBits = this.config.sampleBits;
316
+ }, t2.prototype.startRecord = function() {
317
+ var t3 = this;
318
+ return this.context && this.destroyRecord(), this.initRecorder(), navigator.mediaDevices.getUserMedia({ audio: true }).then(function(e2) {
319
+ t3.audioInput = t3.context.createMediaStreamSource(e2), t3.stream = e2;
320
+ }).then(function() {
321
+ t3.audioInput.connect(t3.analyser), t3.analyser.connect(t3.recorder), t3.recorder.connect(t3.context.destination);
322
+ });
323
+ }, t2.prototype.pauseRecord = function() {
324
+ this.needRecord = false;
325
+ }, t2.prototype.resumeRecord = function() {
326
+ this.needRecord = true;
327
+ }, t2.prototype.stopRecord = function() {
328
+ this.audioInput && this.audioInput.disconnect(), this.source && this.source.stop(), this.recorder.disconnect(), this.analyser.disconnect(), this.needRecord = true;
329
+ }, t2.prototype.destroyRecord = function() {
330
+ return this.clearRecordStatus(), this.stopStream(), this.closeAudioContext();
331
+ }, t2.prototype.getAnalyseData = function() {
332
+ var t3 = new Uint8Array(this.analyser.frequencyBinCount);
333
+ return this.analyser.getByteTimeDomainData(t3), t3;
334
+ }, t2.prototype.getData = function() {
335
+ return this.flat();
336
+ }, t2.prototype.clearRecordStatus = function() {
337
+ this.lBuffer.length = 0, this.rBuffer.length = 0, this.size = 0, this.fileSize = 0, this.PCM = null, this.audioInput = null, this.duration = 0;
338
+ }, t2.prototype.flat = function() {
339
+ var t3 = null, e2 = new Float32Array(0);
340
+ 1 === this.config.numChannels ? t3 = new Float32Array(this.size) : (t3 = new Float32Array(this.size / 2), e2 = new Float32Array(this.size / 2));
341
+ for (var n2 = 0, i2 = 0; i2 < this.lBuffer.length; i2++) t3.set(this.lBuffer[i2], n2), n2 += this.lBuffer[i2].length;
342
+ n2 = 0;
343
+ for (i2 = 0; i2 < this.rBuffer.length; i2++) e2.set(this.rBuffer[i2], n2), n2 += this.rBuffer[i2].length;
344
+ return { left: t3, right: e2 };
345
+ }, t2.prototype.initRecorder = function() {
346
+ var t3 = this;
347
+ this.clearRecordStatus(), this.context = new (window.AudioContext || window.webkitAudioContext)(), this.analyser = this.context.createAnalyser(), this.analyser.fftSize = 2048;
348
+ var e2 = this.context.createScriptProcessor || this.context.createJavaScriptNode;
349
+ this.recorder = e2.apply(this.context, [4096, this.config.numChannels, this.config.numChannels]), this.recorder.onaudioprocess = function(e3) {
350
+ if (t3.needRecord) {
351
+ var n2, i2 = e3.inputBuffer.getChannelData(0), o2 = null;
352
+ t3.lBuffer.push(new Float32Array(i2)), t3.size += i2.length, 2 === t3.config.numChannels && (o2 = e3.inputBuffer.getChannelData(1), t3.rBuffer.push(new Float32Array(o2)), t3.size += o2.length), t3.fileSize = Math.floor(t3.size / Math.max(t3.inputSampleRate / t3.outputSampleRate, 1)) * (t3.oututSampleBits / 8), n2 = 100 * Math.max.apply(Math, i2), t3.duration += 4096 / t3.inputSampleRate, t3.onprocess && t3.onprocess(t3.duration), t3.onprogress && t3.onprogress({ duration: t3.duration, fileSize: t3.fileSize, vol: n2 });
353
+ }
354
+ };
355
+ }, t2.prototype.stopStream = function() {
356
+ this.stream && this.stream.getTracks && (this.stream.getTracks().forEach(function(t3) {
357
+ return t3.stop();
358
+ }), this.stream = null);
359
+ }, t2.prototype.closeAudioContext = function() {
360
+ return this.context && this.context.close && "closed" !== this.context.state ? this.context.close() : new Promise(function(t3) {
361
+ t3();
362
+ });
363
+ }, t2.initUserMedia = function() {
364
+ void 0 === navigator.mediaDevices && (navigator.mediaDevices = {}), void 0 === navigator.mediaDevices.getUserMedia && (navigator.mediaDevices.getUserMedia = function(t3) {
365
+ var e2 = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
366
+ return e2 ? new Promise(function(n2, i2) {
367
+ e2.call(navigator, t3, n2, i2);
368
+ }) : Promise.reject(new Error("浏览器不支持 getUserMedia !"));
369
+ });
370
+ }, t2.prototype.transformIntoPCM = function(t3, e2) {
371
+ var n2 = new Float32Array(t3), o2 = new Float32Array(e2), r = i.compress({ left: n2, right: o2 }, this.inputSampleRate, this.outputSampleRate);
372
+ return i.encodePCM(r, this.oututSampleBits, this.littleEdian);
373
+ }, t2.getPermission = function() {
374
+ return this.initUserMedia(), navigator.mediaDevices.getUserMedia({ audio: true }).then(function(t3) {
375
+ t3 && t3.getTracks().forEach(function(t4) {
376
+ return t4.stop();
377
+ });
378
+ });
379
+ }, t2;
380
+ }();
381
+ e.default = o;
382
+ }]).default;
383
+ });
384
+ })(recorder);
385
+ var recorderExports = recorder.exports;
386
+ var jsAudioRecorder = recorderExports;
387
+ const Recorder = /* @__PURE__ */ getDefaultExportFromCjs(jsAudioRecorder);
388
+ const baseTTSUrl = "http://192.168.3.182:8002";
389
+ const ASR_URL = "http://192.168.3.182:9988/transcribe";
390
+ const _sfc_main = {
391
+ __name: "index",
392
+ props: {
393
+ humans: {
394
+ type: Array,
395
+ default: () => []
396
+ }
397
+ },
398
+ emits: ["loaded", "changed", "paused", "resumed", "audio-ready"],
399
+ setup(__props, { expose: __expose, emit: __emit }) {
400
+ const props = __props;
401
+ const emit = __emit;
402
+ const containerRef = vue.ref(null);
403
+ const canvasRef = vue.ref(null);
404
+ const ctx = vue.ref(null);
405
+ const currentHuman = vue.ref(null);
406
+ const animationId = vue.ref(null);
407
+ const frameIndex = vue.ref(1);
408
+ const timestamp = vue.ref(null);
409
+ const frames = vue.ref({ standby: [], speakStart: [], speakLoop: [], speakEnd: [] });
410
+ const animationState = vue.ref("standby");
411
+ const loopDirection = vue.ref(1);
412
+ const isPaused = vue.ref(false);
413
+ const pauseSnapshot = vue.ref(null);
414
+ const loadFrames = () => {
415
+ frames.value = { standby: [], speakStart: [], speakLoop: [], speakEnd: [] };
416
+ const folder = currentHuman.value.folder;
417
+ const { standbyNum, speakNum } = {
418
+ standbyNum: currentHuman.value.standby.standbyNum,
419
+ speakNum: currentHuman.value.speak.speakNum
420
+ };
421
+ for (let i = 1; i <= standbyNum; i++) {
422
+ const image = new Image();
423
+ image.src = encodeURI(`${folder}/standby/standby (${i}).png`);
424
+ frames.value.standby.push(image);
425
+ }
426
+ const startEnd = Math.floor(speakNum * 0.6);
427
+ const loopEnd = Math.floor(speakNum * 0.9);
428
+ for (let i = 1; i <= startEnd; i++) {
429
+ const image = new Image();
430
+ image.src = encodeURI(`${folder}/speak/speak (${i}).png`);
431
+ frames.value.speakStart.push(image);
432
+ }
433
+ for (let i = startEnd; i <= loopEnd; i++) {
434
+ const image = new Image();
435
+ image.src = encodeURI(`${folder}/speak/speak (${i}).png`);
436
+ frames.value.speakLoop.push(image);
437
+ }
438
+ for (let i = loopEnd; i <= speakNum; i++) {
439
+ const image = new Image();
440
+ image.src = encodeURI(`${folder}/speak/speak (${i}).png`);
441
+ frames.value.speakEnd.push(image);
442
+ }
443
+ };
444
+ const draw = (image) => {
445
+ if (!ctx.value || !image || image.width <= 0 || image.height <= 0) return;
446
+ const canvas = canvasRef.value;
447
+ ctx.value.clearRect(0, 0, canvas.width, canvas.height);
448
+ const scale = Math.min(canvas.width / image.width, canvas.height / image.height);
449
+ const width = image.width * scale;
450
+ const height = image.height * scale;
451
+ const x = (canvas.width - width) / 2;
452
+ const y = canvas.height - height;
453
+ ctx.value.drawImage(image, x, y, width, height);
454
+ };
455
+ const stop = () => {
456
+ if (animationId.value) {
457
+ cancelAnimationFrame(animationId.value);
458
+ animationId.value = null;
459
+ }
460
+ try {
461
+ currentAudio.value.pause();
462
+ } catch (error) {
463
+ }
464
+ frameIndex.value = 1;
465
+ animationState.value = "standby";
466
+ };
467
+ const runAnimation = (state) => {
468
+ stop();
469
+ animationState.value = state;
470
+ loopDirection.value = 1;
471
+ let currentFrames;
472
+ let interval;
473
+ let loopConfig = null;
474
+ switch (state) {
475
+ case "standby":
476
+ currentFrames = frames.value.standby;
477
+ interval = currentHuman.value.standby.interval;
478
+ loopConfig = { type: "pingpong", next: "standby" };
479
+ break;
480
+ case "speak":
481
+ currentFrames = frames.value.speakStart;
482
+ interval = currentHuman.value.speak.interval;
483
+ loopConfig = { type: "once", next: "speakLoop" };
484
+ break;
485
+ case "speakLoop":
486
+ currentFrames = frames.value.speakLoop;
487
+ interval = currentHuman.value.speak.interval;
488
+ loopConfig = { type: "pingpong", next: "speakLoop" };
489
+ break;
490
+ case "speakEnd":
491
+ currentFrames = frames.value.speakEnd;
492
+ interval = currentHuman.value.speak.interval;
493
+ loopConfig = { type: "once", next: "standby" };
494
+ break;
495
+ default:
496
+ return;
497
+ }
498
+ const updateFrame = () => {
499
+ if (!loopConfig) {
500
+ frameIndex.value = frameIndex.value >= currentFrames.length ? 1 : frameIndex.value + 1;
501
+ return false;
502
+ }
503
+ if (loopConfig.type === "once") {
504
+ frameIndex.value++;
505
+ if (frameIndex.value <= currentFrames.length) return false;
506
+ if (loopConfig.next === "standby") {
507
+ standby();
508
+ return true;
509
+ }
510
+ if (loopConfig.next === "speakLoop") {
511
+ frameIndex.value = 1;
512
+ currentFrames = frames.value.speakLoop;
513
+ loopConfig = { type: "pingpong", next: "speakLoop" };
514
+ }
515
+ return false;
516
+ }
517
+ if (loopConfig.type === "pingpong") {
518
+ frameIndex.value += loopDirection.value;
519
+ }
520
+ return false;
521
+ };
522
+ const animate = (time) => {
523
+ if (!timestamp.value) timestamp.value = time;
524
+ if (isPaused.value) {
525
+ animationId.value = requestAnimationFrame(animate);
526
+ return;
527
+ }
528
+ if (time - timestamp.value >= interval) {
529
+ if (loopConfig && loopConfig.type === "pingpong") {
530
+ const nextIndex = frameIndex.value + loopDirection.value;
531
+ if (nextIndex > currentFrames.length) {
532
+ loopDirection.value = -1;
533
+ } else if (nextIndex < 1) {
534
+ loopDirection.value = 1;
535
+ }
536
+ }
537
+ draw(currentFrames[frameIndex.value - 1]);
538
+ const shouldStop = updateFrame();
539
+ if (shouldStop) return;
540
+ timestamp.value = time;
541
+ }
542
+ animationId.value = requestAnimationFrame(animate);
543
+ };
544
+ animationId.value = requestAnimationFrame(animate);
545
+ };
546
+ const standby = () => {
547
+ runAnimation("standby");
548
+ };
549
+ const speak = () => {
550
+ runAnimation("speak");
551
+ };
552
+ const stopSpeaking = () => {
553
+ if (animationState.value === "speak" || animationState.value === "speakLoop") {
554
+ runAnimation("speakEnd");
555
+ } else {
556
+ standby();
557
+ }
558
+ };
559
+ const pause = () => {
560
+ if (isPaused.value) return;
561
+ isPaused.value = true;
562
+ pauseSnapshot.value = {
563
+ state: animationState.value,
564
+ frameIndex: frameIndex.value,
565
+ loopDirection: loopDirection.value
566
+ };
567
+ emit("paused");
568
+ };
569
+ const resume = () => {
570
+ if (!isPaused.value) return;
571
+ isPaused.value = false;
572
+ timestamp.value = null;
573
+ if (pauseSnapshot.value) {
574
+ animationState.value = pauseSnapshot.value.state;
575
+ frameIndex.value = pauseSnapshot.value.frameIndex;
576
+ loopDirection.value = pauseSnapshot.value.loopDirection;
577
+ }
578
+ emit("resumed");
579
+ };
580
+ const waitFramesLoaded = (callback) => {
581
+ let loadedCount = 0;
582
+ const allFrames = [
583
+ ...frames.value.standby,
584
+ ...frames.value.speakStart,
585
+ ...frames.value.speakLoop,
586
+ ...frames.value.speakEnd
587
+ ];
588
+ const checkLoaded = () => {
589
+ loadedCount++;
590
+ if (loadedCount >= allFrames.length) {
591
+ callback();
592
+ }
593
+ };
594
+ allFrames.forEach((img) => {
595
+ if (img.complete) {
596
+ checkLoaded();
597
+ } else {
598
+ img.onload = checkLoaded;
599
+ img.onerror = checkLoaded;
600
+ }
601
+ });
602
+ };
603
+ const init = () => {
604
+ vue.nextTick(() => {
605
+ if (!containerRef.value || !canvasRef.value) return;
606
+ if (!props.humans || props.humans.length === 0) return;
607
+ if (!currentHuman.value) {
608
+ currentHuman.value = props.humans[0];
609
+ }
610
+ const canvas = canvasRef.value;
611
+ const dpr = window.devicePixelRatio || 1;
612
+ const width = containerRef.value.clientWidth;
613
+ const height = containerRef.value.clientHeight;
614
+ canvas.width = width * dpr;
615
+ canvas.height = height * dpr;
616
+ canvas.style.width = width + "px";
617
+ canvas.style.height = height + "px";
618
+ ctx.value = canvas.getContext("2d");
619
+ loadFrames();
620
+ waitFramesLoaded(() => {
621
+ draw(frames.value.standby[0]);
622
+ emit("loaded", currentHuman.value);
623
+ });
624
+ });
625
+ };
626
+ const currentAudio = vue.ref(null);
627
+ const currentTtsRequestId = vue.ref(null);
628
+ const playTTS = async (text) => {
629
+ var _a, _b, _c, _d, _e, _f, _g, _h;
630
+ if (!text || !((_a = currentHuman.value) == null ? void 0 : _a.isMuted)) return;
631
+ if (currentAudio.value) {
632
+ currentAudio.value.pause();
633
+ currentAudio.value = null;
634
+ }
635
+ currentTtsRequestId.value = Date.now();
636
+ const requestId = currentTtsRequestId.value;
637
+ try {
638
+ const cleanText = text.replace(/```[\s\S]*?```/g, "").replace(/`[^`]+`/g, "").replace(/[#*_~]/g, "").replace(/\n+/g, ",").replace(/\s+/g, " ").replace(/[,。!?]{2,}/g, ",").trim();
639
+ if (!cleanText) return;
640
+ const baseUrl = baseTTSUrl;
641
+ const sessionHash = "session_" + Date.now();
642
+ let speed = ((_c = (_b = currentHuman.value) == null ? void 0 : _b.speakSet) == null ? void 0 : _c.speed) || 1;
643
+ let age = ((_e = (_d = currentHuman.value) == null ? void 0 : _d.speakSet) == null ? void 0 : _e.age) || "Young Adult / 青年";
644
+ let sex = ((_g = (_f = currentHuman.value) == null ? void 0 : _f.speakSet) == null ? void 0 : _g.sex) || "Female / 女";
645
+ const data = [cleanText, "Auto", 32, 2, true, speed, null, true, true, sex, age, "Auto", "Auto", "Auto", "Auto"];
646
+ console.log("[OmniVoice] 提交请求:", { text: cleanText, length: cleanText.length, fn_index: 1 });
647
+ const joinRes = await fetch(`${baseUrl}/gradio_api/queue/join`, {
648
+ method: "POST",
649
+ headers: { "Content-Type": "application/json" },
650
+ body: JSON.stringify({ data, session_hash: sessionHash, fn_index: 1, trigger_id: 50 })
651
+ });
652
+ const joinData = await joinRes.json();
653
+ console.log("[OmniVoice] Step1 响应:", joinData);
654
+ console.log("[OmniVoice] Step2: 轮询等待结果");
655
+ let audioUrl = "";
656
+ let maxPolls = 60;
657
+ let pollInterval = 1e3;
658
+ while (!audioUrl && maxPolls > 0) {
659
+ await new Promise((resolve) => setTimeout(resolve, pollInterval));
660
+ maxPolls--;
661
+ try {
662
+ const pollRes = await fetch(`${baseUrl}/gradio_api/queue/data?session_hash=${sessionHash}`);
663
+ const pollText = await pollRes.text();
664
+ const lines = pollText.split("\n");
665
+ for (const line of lines) {
666
+ const trimLine = line.trim();
667
+ if (!trimLine.startsWith("data: ")) continue;
668
+ try {
669
+ const json = JSON.parse(trimLine.replace("data: ", ""));
670
+ console.log("[OmniVoice] 轮询消息:", json);
671
+ if (json.msg === "process_completed" && ((_h = json.output) == null ? void 0 : _h.data)) {
672
+ const fileData = json.output.data[0];
673
+ console.log("[OmniVoice] 获取到音频:", fileData);
674
+ if (fileData == null ? void 0 : fileData.url) audioUrl = fileData.url;
675
+ else if (fileData == null ? void 0 : fileData.path) audioUrl = `${baseUrl}/gradio_api/file=${fileData.path}`;
676
+ else if (typeof fileData === "string") audioUrl = fileData.startsWith("http") ? fileData : `${baseUrl}/gradio_api/file=${fileData}`;
677
+ else if (Array.isArray(fileData) && fileData.length >= 2) {
678
+ const samplingRate = fileData[0];
679
+ const waveform = fileData[1];
680
+ console.log("[OmniVoice] 直接获取到音频数组:", { samplingRate, waveformLength: waveform == null ? void 0 : waveform.length });
681
+ if (samplingRate && waveform && Array.isArray(waveform)) {
682
+ const audioBuffer = new ArrayBuffer(waveform.length * 2);
683
+ const view = new DataView(audioBuffer);
684
+ for (let i = 0; i < waveform.length; i++) {
685
+ view.setInt16(i * 2, waveform[i], true);
686
+ }
687
+ const wavBlob = createWavBlob(audioBuffer, samplingRate, 1, 16);
688
+ const audioObjectUrl = URL.createObjectURL(wavBlob);
689
+ if (currentTtsRequestId.value !== requestId) {
690
+ URL.revokeObjectURL(audioObjectUrl);
691
+ return;
692
+ }
693
+ currentAudio.value = new Audio(audioObjectUrl);
694
+ currentAudio.value.onplaying = () => {
695
+ console.log("[OmniVoice] 音频开始播放");
696
+ speak();
697
+ };
698
+ currentAudio.value.onended = () => {
699
+ console.log("[OmniVoice] 音频播放结束");
700
+ stopSpeaking();
701
+ currentAudio.value = null;
702
+ URL.revokeObjectURL(audioObjectUrl);
703
+ };
704
+ currentAudio.value.onerror = () => {
705
+ console.error("[OmniVoice] 音频播放失败");
706
+ stopSpeaking();
707
+ currentAudio.value = null;
708
+ URL.revokeObjectURL(audioObjectUrl);
709
+ };
710
+ await currentAudio.value.play();
711
+ return;
712
+ }
713
+ }
714
+ break;
715
+ } else if (json.msg === "process_error") {
716
+ console.error("[OmniVoice] 处理错误:", json);
717
+ standby();
718
+ return;
719
+ }
720
+ } catch (e) {
721
+ console.error("[OmniVoice] 解析轮询消息失败:", e);
722
+ }
723
+ }
724
+ } catch (e) {
725
+ console.warn("[OmniVoice] 轮询失败:", e.message);
726
+ }
727
+ }
728
+ if (audioUrl) {
729
+ if (audioUrl.startsWith("/")) audioUrl = baseUrl + audioUrl;
730
+ console.log("[OmniVoice] 下载音频:", audioUrl);
731
+ if (currentTtsRequestId.value !== requestId) return;
732
+ const audioRes = await fetch(audioUrl);
733
+ const audioBlob = await audioRes.blob();
734
+ const audioObjectUrl = URL.createObjectURL(audioBlob);
735
+ currentAudio.value = new Audio(audioObjectUrl);
736
+ currentAudio.value.onplaying = () => {
737
+ console.log("[OmniVoice] 音频开始播放");
738
+ speak();
739
+ };
740
+ currentAudio.value.onended = () => {
741
+ console.log("[OmniVoice] 音频播放结束");
742
+ stopSpeaking();
743
+ currentAudio.value = null;
744
+ URL.revokeObjectURL(audioObjectUrl);
745
+ };
746
+ currentAudio.value.onerror = () => {
747
+ console.error("[OmniVoice] 音频播放失败");
748
+ stopSpeaking();
749
+ currentAudio.value = null;
750
+ URL.revokeObjectURL(audioObjectUrl);
751
+ };
752
+ await currentAudio.value.play();
753
+ } else {
754
+ console.error("[OmniVoice] 未获取到音频");
755
+ standby();
756
+ }
757
+ } catch (e) {
758
+ console.error("[OmniVoice] TTS失败:", e);
759
+ standby();
760
+ }
761
+ };
762
+ const startRecord = async () => {
763
+ try {
764
+ if (recorder2.value) recorder2.value.stop();
765
+ await recorder2.value.start();
766
+ } catch (e) {
767
+ console.error("录音启动失败:", e);
768
+ }
769
+ };
770
+ const stopRecord = async () => {
771
+ if (!recorder2.value) return;
772
+ try {
773
+ recorder2.value.stop();
774
+ const blob = recorder2.value.getWAVBlob();
775
+ if (blob.size < 1e3) {
776
+ return;
777
+ }
778
+ const text = await audioToText(blob);
779
+ console.log("audioToText:", text);
780
+ emit("audio-ready", text);
781
+ } catch (e) {
782
+ console.error("录音处理失败:", e);
783
+ }
784
+ };
785
+ const audioToText = async (blob) => {
786
+ const formData = new FormData();
787
+ formData.append("file", blob, "recorded_audio.wav");
788
+ try {
789
+ const res = await fetch(ASR_URL, {
790
+ method: "POST",
791
+ body: formData
792
+ });
793
+ const resJson = await res.json();
794
+ const text = (resJson == null ? void 0 : resJson.text) || (resJson == null ? void 0 : resJson.text);
795
+ const message = (resJson == null ? void 0 : resJson.success) || (resJson == null ? void 0 : resJson.success);
796
+ return { status: message, text };
797
+ } catch (e) {
798
+ console.error("STT失败:", e);
799
+ return { status: e, text: "" };
800
+ }
801
+ };
802
+ const createWavBlob = (audioBuffer, sampleRate, channels, bitsPerSample) => {
803
+ const bytesPerSample = bitsPerSample / 8;
804
+ const blockAlign = channels * bytesPerSample;
805
+ const dataSize = audioBuffer.byteLength;
806
+ const buffer = new ArrayBuffer(44 + dataSize);
807
+ const view = new DataView(buffer);
808
+ view.setUint8(0, 82);
809
+ view.setUint8(1, 73);
810
+ view.setUint8(2, 70);
811
+ view.setUint8(3, 70);
812
+ view.setUint32(4, 36 + dataSize, true);
813
+ view.setUint8(8, 87);
814
+ view.setUint8(9, 65);
815
+ view.setUint8(10, 86);
816
+ view.setUint8(11, 69);
817
+ view.setUint8(12, 102);
818
+ view.setUint8(13, 109);
819
+ view.setUint8(14, 116);
820
+ view.setUint8(15, 32);
821
+ view.setUint32(16, 16, true);
822
+ view.setUint16(20, 1, true);
823
+ view.setUint16(22, channels, true);
824
+ view.setUint32(24, sampleRate, true);
825
+ view.setUint32(28, sampleRate * blockAlign, true);
826
+ view.setUint16(32, blockAlign, true);
827
+ view.setUint16(34, bitsPerSample, true);
828
+ view.setUint8(36, 100);
829
+ view.setUint8(37, 97);
830
+ view.setUint8(38, 116);
831
+ view.setUint8(39, 97);
832
+ view.setUint32(40, dataSize, true);
833
+ const audioData = new Uint8Array(audioBuffer);
834
+ const destData = new Uint8Array(buffer, 44);
835
+ destData.set(audioData);
836
+ return new Blob([buffer], { type: "audio/wav" });
837
+ };
838
+ let recorder2 = vue.ref(null);
839
+ const initRecorder = () => {
840
+ console.log("initRecorder");
841
+ if (!recorder2.value) {
842
+ recorder2.value = new Recorder({
843
+ sampleBits: 16,
844
+ sampleRate: 16e3,
845
+ numChannels: 1
846
+ });
847
+ }
848
+ };
849
+ __expose({
850
+ standby,
851
+ speak,
852
+ stopSpeaking,
853
+ pause,
854
+ resume,
855
+ playTTS,
856
+ startRecord,
857
+ stopRecord
858
+ });
859
+ vue.watch(() => props.humans, (val) => {
860
+ if (val && val.length > 0 && !currentHuman.value) {
861
+ init();
862
+ }
863
+ }, { deep: true });
864
+ vue.onMounted(() => {
865
+ initRecorder();
866
+ init();
867
+ });
868
+ vue.onUnmounted(() => {
869
+ stop();
870
+ if (recorder2.value) {
871
+ recorder2.value.stop();
872
+ }
873
+ });
874
+ return (_ctx, _cache) => {
875
+ return vue.openBlock(), vue.createElementBlock("div", {
876
+ class: "digital-human",
877
+ ref_key: "containerRef",
878
+ ref: containerRef
879
+ }, [
880
+ vue.createElementVNode("canvas", {
881
+ ref_key: "canvasRef",
882
+ ref: canvasRef
883
+ }, null, 512)
884
+ ], 512);
885
+ };
886
+ }
887
+ };
888
+ const DigitalHuman = /* @__PURE__ */ _export_sfc(_sfc_main, [["__scopeId", "data-v-dd386539"]]);
889
+ DigitalHuman.install = (app) => app.component("DigitalHuman", DigitalHuman);
890
+ const components = [DemoButton, DemoInput, DigitalHuman];
891
+ const install = (app) => {
892
+ components.forEach((comp) => app.use(comp));
893
+ };
894
+ const index = { install };
895
+ exports.DemoButton = DemoButton;
896
+ exports.DemoInput = DemoInput;
897
+ exports.DigitalHuman = DigitalHuman;
898
+ exports.default = index;
@@ -447,7 +447,7 @@ const _sfc_main = {
447
447
  const width = image.width * scale;
448
448
  const height = image.height * scale;
449
449
  const x = (canvas.width - width) / 2;
450
- const y = (canvas.height - height) / 2;
450
+ const y = canvas.height - height;
451
451
  ctx.value.drawImage(image, x, y, width, height);
452
452
  };
453
453
  const stop = () => {
@@ -455,6 +455,10 @@ const _sfc_main = {
455
455
  cancelAnimationFrame(animationId.value);
456
456
  animationId.value = null;
457
457
  }
458
+ try {
459
+ currentAudio.value.pause();
460
+ } catch (error) {
461
+ }
458
462
  frameIndex.value = 1;
459
463
  animationState.value = "standby";
460
464
  };
@@ -610,7 +614,6 @@ const _sfc_main = {
610
614
  canvas.style.width = width + "px";
611
615
  canvas.style.height = height + "px";
612
616
  ctx.value = canvas.getContext("2d");
613
- ctx.value.scale(dpr, dpr);
614
617
  loadFrames();
615
618
  waitFramesLoaded(() => {
616
619
  draw(frames.value.standby[0]);
@@ -771,13 +774,13 @@ const _sfc_main = {
771
774
  return;
772
775
  }
773
776
  const text = await audioToText(blob);
777
+ console.log("audioToText:", text);
774
778
  emit("audio-ready", text);
775
779
  } catch (e) {
776
780
  console.error("录音处理失败:", e);
777
781
  }
778
782
  };
779
783
  const audioToText = async (blob) => {
780
- var _a;
781
784
  const formData = new FormData();
782
785
  formData.append("file", blob, "recorded_audio.wav");
783
786
  try {
@@ -785,10 +788,13 @@ const _sfc_main = {
785
788
  method: "POST",
786
789
  body: formData
787
790
  });
788
- console.log("STT结果:", res);
789
- const text = ((_a = res.data) == null ? void 0 : _a.text) || res.text;
791
+ const resJson = await res.json();
792
+ const text = (resJson == null ? void 0 : resJson.text) || (resJson == null ? void 0 : resJson.text);
793
+ const message = (resJson == null ? void 0 : resJson.success) || (resJson == null ? void 0 : resJson.success);
794
+ return { status: message, text };
790
795
  } catch (e) {
791
796
  console.error("STT失败:", e);
797
+ return { status: e, text: "" };
792
798
  }
793
799
  };
794
800
  const createWavBlob = (audioBuffer, sampleRate, channels, bitsPerSample) => {
@@ -877,7 +883,7 @@ const _sfc_main = {
877
883
  };
878
884
  }
879
885
  };
880
- const DigitalHuman = /* @__PURE__ */ _export_sfc(_sfc_main, [["__scopeId", "data-v-6406e025"]]);
886
+ const DigitalHuman = /* @__PURE__ */ _export_sfc(_sfc_main, [["__scopeId", "data-v-dd386539"]]);
881
887
  DigitalHuman.install = (app) => app.component("DigitalHuman", DigitalHuman);
882
888
  const components = [DemoButton, DemoInput, DigitalHuman];
883
889
  const install = (app) => {
package/dist/style.css CHANGED
@@ -1 +1 @@
1
- .demo-btn[data-v-9a48516a]{padding:6px 14px;border-radius:4px;border:none;cursor:pointer;font-size:14px}.primary[data-v-9a48516a]{background:#409eff;color:#fff}.success[data-v-9a48516a]{background:#67c23a;color:#fff}.warning[data-v-9a48516a]{background:#e6a23c;color:#fff}.demo-input-wrap[data-v-28a3493c]{display:inline-flex;align-items:center;border:1px solid #dcdcdc;border-radius:4px;padding:0 10px}.demo-input-wrap[data-v-28a3493c]:focus-within{border-color:#409eff}.demo-input[data-v-28a3493c]{border:none;outline:none;padding:8px 6px;flex:1}.prefix[data-v-28a3493c],.suffix[data-v-28a3493c]{color:#909399}.digital-human[data-v-6406e025]{width:100%;height:100%;display:flex;align-items:center;justify-content:center}.digital-human canvas[data-v-6406e025]{max-width:100%;max-height:100%}
1
+ .demo-btn[data-v-9a48516a]{padding:6px 14px;border-radius:4px;border:none;cursor:pointer;font-size:14px}.primary[data-v-9a48516a]{background:#409eff;color:#fff}.success[data-v-9a48516a]{background:#67c23a;color:#fff}.warning[data-v-9a48516a]{background:#e6a23c;color:#fff}.demo-input-wrap[data-v-28a3493c]{display:inline-flex;align-items:center;border:1px solid #dcdcdc;border-radius:4px;padding:0 10px}.demo-input-wrap[data-v-28a3493c]:focus-within{border-color:#409eff}.demo-input[data-v-28a3493c]{border:none;outline:none;padding:8px 6px;flex:1}.prefix[data-v-28a3493c],.suffix[data-v-28a3493c]{color:#909399}.digital-human[data-v-dd386539]{width:100%;height:100%;display:flex;align-items:center;justify-content:center}.digital-human canvas[data-v-dd386539]{max-width:100%;max-height:100%}
package/package.json CHANGED
@@ -1,14 +1,14 @@
1
1
  {
2
2
  "name": "ruiyun-human",
3
- "version": "1.0.2",
3
+ "version": "1.0.4",
4
4
  "type": "module",
5
5
  "description": "数字人初步实现",
6
- "main": "./dist/ruiyun-human.umd.js",
6
+ "main": "./dist/ruiyun-human.cjs.js",
7
7
  "module": "./dist/ruiyun-human.es.js",
8
8
  "exports": {
9
9
  ".": {
10
10
  "import": "./dist/ruiyun-human.es.js",
11
- "require": "./dist/ruiyun-human.umd.js"
11
+ "require": "./dist/ruiyun-human.cjs.js"
12
12
  }
13
13
  },
14
14
  "files": [
Binary file
@@ -1,11 +0,0 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("vue")):"function"==typeof define&&define.amd?define(["exports","vue"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).RuiYunHuman={},e.Vue)}(this,function(e,t){"use strict";const _export_sfc=(e,t)=>{const a=e.__vccOpts||e;for(const[o,r]of t)a[o]=r;return a},a=_export_sfc({__name:"index",props:{type:{type:String,default:"primary"}},emits:["click"],setup:e=>(a,o)=>(t.openBlock(),t.createElementBlock("button",{class:t.normalizeClass(["demo-btn",e.type]),onClick:o[0]||(o[0]=e=>a.$emit("click"))},[t.renderSlot(a.$slots,"default",{},void 0,!0)],2))},[["__scopeId","data-v-9a48516a"]]);a.install=e=>e.component("DemoButton",a);const o={class:"demo-input-wrap"},r={key:0,class:"prefix"},s=["type","placeholder","value","disabled"],l={key:1,class:"suffix"},u=_export_sfc({__name:"index",props:{modelValue:{type:[String,Number],default:""},placeholder:{type:String,default:"请输入内容"},inputType:{type:String,default:"text"},disabled:{type:Boolean,default:!1}},emits:["update:modelValue","focus","blur"],setup(e,{emit:a}){const u=a,handleInput=e=>u("update:modelValue",e.target.value);return(a,u)=>(t.openBlock(),t.createElementBlock("div",o,[a.$slots.prefix?(t.openBlock(),t.createElementBlock("span",r,[t.renderSlot(a.$slots,"prefix",{},void 0,!0)])):t.createCommentVNode("",!0),t.createElementVNode("input",{class:"demo-input",type:e.inputType,placeholder:e.placeholder,value:e.modelValue,disabled:e.disabled,onInput:handleInput,onFocus:u[0]||(u[0]=e=>a.$emit("focus")),onBlur:u[1]||(u[1]=e=>a.$emit("blur"))},null,40,s),a.$slots.suffix?(t.openBlock(),t.createElementBlock("span",l,[t.renderSlot(a.$slots,"suffix",{},void 0,!0)])):t.createCommentVNode("",!0)]))}},[["__scopeId","data-v-28a3493c"]]);u.install=e=>e.component("DemoInput",u);"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;function getDefaultExportFromCjs(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var c={exports:{}};
2
- /*!
3
- *
4
- * js-audio-recorder - js audio recorder plugin
5
- *
6
- * @version v1.0.7
7
- * @homepage https://github.com/2fps/recorder
8
- * @author 2fps <echoweb@126.com> (https://www.zhuyuntao.cn)
9
- * @license MIT
10
- *
11
- */c.exports=function(e){var t={};function n(a){if(t[a])return t[a].exports;var o=t[a]={i:a,l:!1,exports:{}};return e[a].call(o.exports,o,o.exports,n),o.l=!0,o.exports}return n.m=e,n.c=t,n.d=function(e,t,a){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:a})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var a=Object.create(null);if(n.r(a),Object.defineProperty(a,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)n.d(a,o,function(t){return e[t]}.bind(null,o));return a},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=1)}([function(e,t,a){function i(e,t,a){for(var o=0;o<a.length;o++)e.setUint8(t+o,a.charCodeAt(o))}Object.defineProperty(t,"__esModule",{value:!0}),t.compress=function(e,t,a){for(var o=t/a,r=Math.max(o,1),s=e.left,l=e.right,u=Math.floor((s.length+l.length)/o),c=new Float32Array(u),f=0,v=0;f<u;){var y=Math.floor(v);c[f]=s[y],f++,l.length&&(c[f]=l[y],f++),v+=r}return c},t.encodePCM=function(e,t,a){void 0===a&&(a=!0);var o=0,r=e.length*(t/8),s=new ArrayBuffer(r),l=new DataView(s);if(8===t)for(var u=0;u<e.length;u++,o++){var c=(f=Math.max(-1,Math.min(1,e[u])))<0?128*f:127*f;c=+c+128,l.setInt8(o,c)}else for(u=0;u<e.length;u++,o+=2){var f=Math.max(-1,Math.min(1,e[u]));l.setInt16(o,f<0?32768*f:32767*f,a)}return l},t.encodeWAV=function(e,t,a,o,r,s){void 0===s&&(s=!0);var l=a>t?t:a,u=r,c=new ArrayBuffer(44+e.byteLength),f=new DataView(c),v=o,y=0;i(f,y,"RIFF"),y+=4,f.setUint32(y,36+e.byteLength,s),i(f,y+=4,"WAVE"),i(f,y+=4,"fmt "),y+=4,f.setUint32(y,16,s),y+=4,f.setUint16(y,1,s),y+=2,f.setUint16(y,v,s),y+=2,f.setUint32(y,l,s),y+=4,f.setUint32(y,v*l*(u/8),s),y+=4,f.setUint16(y,v*(u/8),s),y+=2,f.setUint16(y,u,s),i(f,y+=2,"data"),y+=4,f.setUint32(y,e.byteLength,s),y+=4;for(var g=0;g<e.byteLength;)f.setUint8(y,e.getUint8(g)),y++,g++;return f}},function(e,t,a){var o,r=this&&this.__extends||(o=function(e,t){return(o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var a in t)t.hasOwnProperty(a)&&(e[a]=t[a])})(e,t)},function(e,t){function n2(){this.constructor=e}o(e,t),e.prototype=null===t?Object.create(t):(n2.prototype=t.prototype,new n2)});Object.defineProperty(t,"__esModule",{value:!0});var s=a(2),l=a(0),u=a(3),c=function(e){function e2(t){void 0===t&&(t={});var a=e.call(this,t)||this;return a.isrecording=!1,a.ispause=!1,a.isplaying=!1,a}return r(e2,e),e2.prototype.setOption=function(e){void 0===e&&(e={}),this.setNewOption(e)},e2.prototype.start=function(){return this.isrecording?Promise.reject():(this.isrecording=!0,this.startRecord())},e2.prototype.pause=function(){this.isrecording&&!this.ispause&&(this.ispause=!0,this.pauseRecord())},e2.prototype.resume=function(){this.isrecording&&this.ispause&&(this.ispause=!1,this.resumeRecord())},e2.prototype.stop=function(){this.isrecording&&(this.isrecording=!1,this.ispause=!1,this.stopRecord())},e2.prototype.play=function(){this.stop(),this.isplaying=!0,this.onplay&&this.onplay(),u.default.addPlayEnd(this.onplayend);var e=this.getWAV();e.byteLength>44&&u.default.play(e.buffer)},e2.prototype.getPlayTime=function(){return u.default.getPlayTime()},e2.prototype.pausePlay=function(){!this.isrecording&&this.isplaying&&(this.isplaying=!1,this.onpauseplay&&this.onpauseplay(),u.default.pausePlay())},e2.prototype.resumePlay=function(){this.isrecording||this.isplaying||(this.isplaying=!0,this.onresumeplay&&this.onresumeplay(),u.default.resumePlay())},e2.prototype.stopPlay=function(){this.isrecording||(this.isplaying=!1,this.onstopplay&&this.onstopplay(),u.default.stopPlay())},e2.prototype.destroy=function(){return u.default.destroyPlay(),this.destroyRecord()},e2.prototype.getRecordAnalyseData=function(){return this.getAnalyseData()},e2.prototype.getPlayAnalyseData=function(){return u.default.getAnalyseData()},e2.prototype.getPCM=function(){this.stop();var e=this.getData();return e=l.compress(e,this.inputSampleRate,this.outputSampleRate),l.encodePCM(e,this.oututSampleBits,this.littleEdian)},e2.prototype.getPCMBlob=function(){return new Blob([this.getPCM()])},e2.prototype.downloadPCM=function(e){void 0===e&&(e="recorder");var t=this.getPCMBlob();s.downloadPCM(t,e)},e2.prototype.getWAV=function(){var e=this.getPCM();return l.encodeWAV(e,this.inputSampleRate,this.outputSampleRate,this.config.numChannels,this.oututSampleBits,this.littleEdian)},e2.prototype.getWAVBlob=function(){return new Blob([this.getWAV()],{type:"audio/wav"})},e2.prototype.downloadWAV=function(e){void 0===e&&(e="recorder");var t=this.getWAVBlob();s.downloadWAV(t,e)},e2.prototype.download=function(e,t,a){s.download(e,t,a)},e2.prototype.getChannelData=function(){var e=this.getPCM(),t=e.byteLength,a=this.littleEdian,o={left:null,right:null};if(2===this.config.numChannels){var r=new DataView(new ArrayBuffer(t/2)),s=new DataView(new ArrayBuffer(t/2));if(16===this.config.sampleBits)for(var l=0;l<t/2;l+=2)r.setInt16(l,e.getInt16(2*l,a),a),s.setInt16(l,e.getInt16(2*l+2,a),a);else for(l=0;l<t/2;l+=2)r.setInt8(l,e.getInt8(2*l)),s.setInt8(l,e.getInt8(2*l+1));o.left=r,o.right=s}else o.left=e;return o},e2}(a(5).default);t.default=c},function(e,t,a){function i(e,t,a){var o=document.createElement("a");o.href=window.URL.createObjectURL(e),o.download=t+"."+a,o.click()}Object.defineProperty(t,"__esModule",{value:!0}),t.downloadWAV=function(e,t){void 0===t&&(t="recorder"),i(e,t,"wav")},t.downloadPCM=function(e,t){void 0===t&&(t="recorder"),i(e,t,"pcm")},t.download=function(e,t,a){return i(e,t,a)}},function(e,t,a){Object.defineProperty(t,"__esModule",{value:!0});var o=a(4),r=null,s=0,l=0,u=null,c=null,f=null,v=!1,y=0,p=function(){};function d(){return v=!1,u.decodeAudioData(f.slice(0),function(e){(r=u.createBufferSource()).onended=function(){v||(y=u.currentTime-l+s,p())},r.buffer=e,r.connect(c),c.connect(u.destination),r.start(0,s),l=u.currentTime},function(e){o.throwError(e)})}function h(){r&&(r.stop(),r=null)}var g=function(){function t2(){}return t2.play=function(e){return u||(u=new(window.AudioContext||window.webkitAudioContext),(c=u.createAnalyser()).fftSize=2048),this.stopPlay(),f=e,y=0,d()},t2.pausePlay=function(){h(),s+=u.currentTime-l,v=!0},t2.resumePlay=function(){return d()},t2.stopPlay=function(){s=0,f=null,h()},t2.destroyPlay=function(){this.stopPlay()},t2.getAnalyseData=function(){var e=new Uint8Array(c.frequencyBinCount);return c.getByteTimeDomainData(e),e},t2.addPlayEnd=function(e){void 0===e&&(e=function(){}),p=e},t2.getPlayTime=function(){var e=v?s:u.currentTime-l+s;return y||e},t2}();t.default=g},function(e,t,a){Object.defineProperty(t,"__esModule",{value:!0}),t.throwError=function(e){throw new Error(e)}},function(e,t,a){Object.defineProperty(t,"__esModule",{value:!0});var o=a(0),r=function(){function t2(e){void 0===e&&(e={}),this.size=0,this.lBuffer=[],this.rBuffer=[],this.tempPCM=[],this.inputSampleBits=16,this.fileSize=0,this.duration=0,this.needRecord=!0;var t,a=new(window.AudioContext||window.webkitAudioContext);this.inputSampleRate=a.sampleRate,this.setNewOption(e),this.littleEdian=(t=new ArrayBuffer(2),new DataView(t).setInt16(0,256,!0),256===new Int16Array(t)[0]),t2.initUserMedia()}return t2.prototype.setNewOption=function(e){void 0===e&&(e={}),this.config={sampleBits:~[8,16].indexOf(e.sampleBits)?e.sampleBits:16,sampleRate:~[8e3,11025,16e3,22050,24e3,44100,48e3].indexOf(e.sampleRate)?e.sampleRate:this.inputSampleRate,numChannels:~[1,2].indexOf(e.numChannels)?e.numChannels:1},this.outputSampleRate=this.config.sampleRate,this.oututSampleBits=this.config.sampleBits},t2.prototype.startRecord=function(){var e=this;return this.context&&this.destroyRecord(),this.initRecorder(),navigator.mediaDevices.getUserMedia({audio:!0}).then(function(t){e.audioInput=e.context.createMediaStreamSource(t),e.stream=t}).then(function(){e.audioInput.connect(e.analyser),e.analyser.connect(e.recorder),e.recorder.connect(e.context.destination)})},t2.prototype.pauseRecord=function(){this.needRecord=!1},t2.prototype.resumeRecord=function(){this.needRecord=!0},t2.prototype.stopRecord=function(){this.audioInput&&this.audioInput.disconnect(),this.source&&this.source.stop(),this.recorder.disconnect(),this.analyser.disconnect(),this.needRecord=!0},t2.prototype.destroyRecord=function(){return this.clearRecordStatus(),this.stopStream(),this.closeAudioContext()},t2.prototype.getAnalyseData=function(){var e=new Uint8Array(this.analyser.frequencyBinCount);return this.analyser.getByteTimeDomainData(e),e},t2.prototype.getData=function(){return this.flat()},t2.prototype.clearRecordStatus=function(){this.lBuffer.length=0,this.rBuffer.length=0,this.size=0,this.fileSize=0,this.PCM=null,this.audioInput=null,this.duration=0},t2.prototype.flat=function(){var e=null,t=new Float32Array(0);1===this.config.numChannels?e=new Float32Array(this.size):(e=new Float32Array(this.size/2),t=new Float32Array(this.size/2));for(var a=0,o=0;o<this.lBuffer.length;o++)e.set(this.lBuffer[o],a),a+=this.lBuffer[o].length;for(a=0,o=0;o<this.rBuffer.length;o++)t.set(this.rBuffer[o],a),a+=this.rBuffer[o].length;return{left:e,right:t}},t2.prototype.initRecorder=function(){var e=this;this.clearRecordStatus(),this.context=new(window.AudioContext||window.webkitAudioContext),this.analyser=this.context.createAnalyser(),this.analyser.fftSize=2048;var t=this.context.createScriptProcessor||this.context.createJavaScriptNode;this.recorder=t.apply(this.context,[4096,this.config.numChannels,this.config.numChannels]),this.recorder.onaudioprocess=function(t){if(e.needRecord){var a,o=t.inputBuffer.getChannelData(0),r=null;e.lBuffer.push(new Float32Array(o)),e.size+=o.length,2===e.config.numChannels&&(r=t.inputBuffer.getChannelData(1),e.rBuffer.push(new Float32Array(r)),e.size+=r.length),e.fileSize=Math.floor(e.size/Math.max(e.inputSampleRate/e.outputSampleRate,1))*(e.oututSampleBits/8),a=100*Math.max.apply(Math,o),e.duration+=4096/e.inputSampleRate,e.onprocess&&e.onprocess(e.duration),e.onprogress&&e.onprogress({duration:e.duration,fileSize:e.fileSize,vol:a})}}},t2.prototype.stopStream=function(){this.stream&&this.stream.getTracks&&(this.stream.getTracks().forEach(function(e){return e.stop()}),this.stream=null)},t2.prototype.closeAudioContext=function(){return this.context&&this.context.close&&"closed"!==this.context.state?this.context.close():new Promise(function(e){e()})},t2.initUserMedia=function(){void 0===navigator.mediaDevices&&(navigator.mediaDevices={}),void 0===navigator.mediaDevices.getUserMedia&&(navigator.mediaDevices.getUserMedia=function(e){var t=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia;return t?new Promise(function(a,o){t.call(navigator,e,a,o)}):Promise.reject(new Error("浏览器不支持 getUserMedia !"))})},t2.prototype.transformIntoPCM=function(e,t){var a=new Float32Array(e),r=new Float32Array(t),s=o.compress({left:a,right:r},this.inputSampleRate,this.outputSampleRate);return o.encodePCM(s,this.oututSampleBits,this.littleEdian)},t2.getPermission=function(){return this.initUserMedia(),navigator.mediaDevices.getUserMedia({audio:!0}).then(function(e){e&&e.getTracks().forEach(function(e){return e.stop()})})},t2}();t.default=r}]).default;const f=getDefaultExportFromCjs(c.exports),v=_export_sfc({__name:"index",props:{humans:{type:Array,default:()=>[]}},emits:["loaded","changed","paused","resumed","audio-ready"],setup(e,{expose:a,emit:o}){const r=e,s=o,l=t.ref(null),u=t.ref(null),c=t.ref(null),v=t.ref(null),y=t.ref(null),g=t.ref(1),m=t.ref(null),w=t.ref({standby:[],speakStart:[],speakLoop:[],speakEnd:[]}),b=t.ref("standby"),k=t.ref(1),U=t.ref(!1),x=t.ref(null),draw=e=>{if(!c.value||!e||e.width<=0||e.height<=0)return;const t=u.value;c.value.clearRect(0,0,t.width,t.height);const a=Math.min(t.width/e.width,t.height/e.height),o=e.width*a,r=e.height*a,s=(t.width-o)/2,l=(t.height-r)/2;c.value.drawImage(e,s,l,o,r)},stop=()=>{y.value&&(cancelAnimationFrame(y.value),y.value=null),g.value=1,b.value="standby"},runAnimation=e=>{let t,a;stop(),b.value=e,k.value=1;let o=null;switch(e){case"standby":t=w.value.standby,a=v.value.standby.interval,o={type:"pingpong",next:"standby"};break;case"speak":t=w.value.speakStart,a=v.value.speak.interval,o={type:"once",next:"speakLoop"};break;case"speakLoop":t=w.value.speakLoop,a=v.value.speak.interval,o={type:"pingpong",next:"speakLoop"};break;case"speakEnd":t=w.value.speakEnd,a=v.value.speak.interval,o={type:"once",next:"standby"};break;default:return}const animate=e=>{if(m.value||(m.value=e),U.value)y.value=requestAnimationFrame(animate);else{if(e-m.value>=a){if(o&&"pingpong"===o.type){const e=g.value+k.value;e>t.length?k.value=-1:e<1&&(k.value=1)}draw(t[g.value-1]);if(o?"once"===o.type?(g.value++,!(g.value<=t.length||("standby"===o.next?(standby(),0):("speakLoop"===o.next&&(g.value=1,t=w.value.speakLoop,o={type:"pingpong",next:"speakLoop"}),1)))):("pingpong"===o.type&&(g.value+=k.value),!1):(g.value=g.value>=t.length?1:g.value+1,!1))return;m.value=e}y.value=requestAnimationFrame(animate)}};y.value=requestAnimationFrame(animate)},standby=()=>{runAnimation("standby")},speak=()=>{runAnimation("speak")},stopSpeaking=()=>{"speak"===b.value||"speakLoop"===b.value?runAnimation("speakEnd"):standby()},init=()=>{t.nextTick(()=>{if(!l.value||!u.value)return;if(!r.humans||0===r.humans.length)return;v.value||(v.value=r.humans[0]);const e=u.value,t=window.devicePixelRatio||1,a=l.value.clientWidth,o=l.value.clientHeight;e.width=a*t,e.height=o*t,e.style.width=a+"px",e.style.height=o+"px",c.value=e.getContext("2d"),c.value.scale(t,t),(()=>{w.value={standby:[],speakStart:[],speakLoop:[],speakEnd:[]};const e=v.value.folder,{standbyNum:t,speakNum:a}={standbyNum:v.value.standby.standbyNum,speakNum:v.value.speak.speakNum};for(let s=1;s<=t;s++){const t=new Image;t.src=encodeURI(`${e}/standby/standby (${s}).png`),w.value.standby.push(t)}const o=Math.floor(.6*a),r=Math.floor(.9*a);for(let s=1;s<=o;s++){const t=new Image;t.src=encodeURI(`${e}/speak/speak (${s}).png`),w.value.speakStart.push(t)}for(let s=o;s<=r;s++){const t=new Image;t.src=encodeURI(`${e}/speak/speak (${s}).png`),w.value.speakLoop.push(t)}for(let s=r;s<=a;s++){const t=new Image;t.src=encodeURI(`${e}/speak/speak (${s}).png`),w.value.speakEnd.push(t)}})(),(e=>{let t=0;const a=[...w.value.standby,...w.value.speakStart,...w.value.speakLoop,...w.value.speakEnd],checkLoaded=()=>{t++,t>=a.length&&e()};a.forEach(e=>{e.complete?checkLoaded():(e.onload=checkLoaded,e.onerror=checkLoaded)})})(()=>{draw(w.value.standby[0]),s("loaded",v.value)})})},A=t.ref(null),R=t.ref(null),audioToText=async e=>{var t;const a=new FormData;a.append("file",e,"recorded_audio.wav");try{const e=await fetch("http://192.168.3.182:9988/transcribe",{method:"POST",body:a});(null==(t=e.data)?void 0:t.text)||e.text}catch(o){}},createWavBlob=(e,t,a,o)=>{const r=a*(o/8),s=e.byteLength,l=new ArrayBuffer(44+s),u=new DataView(l);u.setUint8(0,82),u.setUint8(1,73),u.setUint8(2,70),u.setUint8(3,70),u.setUint32(4,36+s,!0),u.setUint8(8,87),u.setUint8(9,65),u.setUint8(10,86),u.setUint8(11,69),u.setUint8(12,102),u.setUint8(13,109),u.setUint8(14,116),u.setUint8(15,32),u.setUint32(16,16,!0),u.setUint16(20,1,!0),u.setUint16(22,a,!0),u.setUint32(24,t,!0),u.setUint32(28,t*r,!0),u.setUint16(32,r,!0),u.setUint16(34,o,!0),u.setUint8(36,100),u.setUint8(37,97),u.setUint8(38,116),u.setUint8(39,97),u.setUint32(40,s,!0);const c=new Uint8Array(e);return new Uint8Array(l,44).set(c),new Blob([l],{type:"audio/wav"})};let S=t.ref(null);return a({standby:standby,speak:speak,stopSpeaking:stopSpeaking,pause:()=>{U.value||(U.value=!0,x.value={state:b.value,frameIndex:g.value,loopDirection:k.value},s("paused"))},resume:()=>{U.value&&(U.value=!1,m.value=null,x.value&&(b.value=x.value.state,g.value=x.value.frameIndex,k.value=x.value.loopDirection),s("resumed"))},playTTS:async e=>{var t,a,o,r,s,l,u,c;if(!e||!(null==(t=v.value)?void 0:t.isMuted))return;A.value&&(A.value.pause(),A.value=null),R.value=Date.now();const f=R.value;try{const t=e.replace(/```[\s\S]*?```/g,"").replace(/`[^`]+`/g,"").replace(/[#*_~]/g,"").replace(/\n+/g,",").replace(/\s+/g," ").replace(/[,。!?]{2,}/g,",").trim();if(!t)return;const g="http://192.168.3.182:8002",m="session_"+Date.now();let w=(null==(o=null==(a=v.value)?void 0:a.speakSet)?void 0:o.speed)||1,b=(null==(s=null==(r=v.value)?void 0:r.speakSet)?void 0:s.age)||"Young Adult / 青年";const k=[t,"Auto",32,2,!0,w,null,!0,!0,(null==(u=null==(l=v.value)?void 0:l.speakSet)?void 0:u.sex)||"Female / 女",b,"Auto","Auto","Auto","Auto"],U=await fetch(`${g}/gradio_api/queue/join`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({data:k,session_hash:m,fn_index:1,trigger_id:50})});await U.json();let x="",S=60,_=1e3;for(;!x&&S>0;){await new Promise(e=>setTimeout(e,_)),S--;try{const e=await fetch(`${g}/gradio_api/queue/data?session_hash=${m}`),t=(await e.text()).split("\n");for(const a of t){const e=a.trim();if(e.startsWith("data: "))try{const t=JSON.parse(e.replace("data: ",""));if("process_completed"===t.msg&&(null==(c=t.output)?void 0:c.data)){const e=t.output.data[0];if(null==e?void 0:e.url)x=e.url;else if(null==e?void 0:e.path)x=`${g}/gradio_api/file=${e.path}`;else if("string"==typeof e)x=e.startsWith("http")?e:`${g}/gradio_api/file=${e}`;else if(Array.isArray(e)&&e.length>=2){const t=e[0],a=e[1];if(t&&a&&Array.isArray(a)){const e=new ArrayBuffer(2*a.length),o=new DataView(e);for(let t=0;t<a.length;t++)o.setInt16(2*t,a[t],!0);const r=createWavBlob(e,t,1,16),s=URL.createObjectURL(r);return R.value!==f?void URL.revokeObjectURL(s):(A.value=new Audio(s),A.value.onplaying=()=>{speak()},A.value.onended=()=>{stopSpeaking(),A.value=null,URL.revokeObjectURL(s)},A.value.onerror=()=>{stopSpeaking(),A.value=null,URL.revokeObjectURL(s)},void(await A.value.play()))}}break}if("process_error"===t.msg)return void standby()}catch(y){}}}catch(y){}}if(x){if(x.startsWith("/")&&(x=g+x),R.value!==f)return;const e=await fetch(x),t=await e.blob(),a=URL.createObjectURL(t);A.value=new Audio(a),A.value.onplaying=()=>{speak()},A.value.onended=()=>{stopSpeaking(),A.value=null,URL.revokeObjectURL(a)},A.value.onerror=()=>{stopSpeaking(),A.value=null,URL.revokeObjectURL(a)},await A.value.play()}else standby()}catch(y){standby()}},startRecord:async()=>{try{S.value&&S.value.stop(),await S.value.start()}catch(e){}},stopRecord:async()=>{if(S.value)try{S.value.stop();const e=S.value.getWAVBlob();if(e.size<1e3)return;const t=await audioToText(e);s("audio-ready",t)}catch(e){}}}),t.watch(()=>r.humans,e=>{e&&e.length>0&&!v.value&&init()},{deep:!0}),t.onMounted(()=>{S.value||(S.value=new f({sampleBits:16,sampleRate:16e3,numChannels:1})),init()}),t.onUnmounted(()=>{stop(),S.value&&S.value.stop()}),(e,a)=>(t.openBlock(),t.createElementBlock("div",{class:"digital-human",ref_key:"containerRef",ref:l},[t.createElementVNode("canvas",{ref_key:"canvasRef",ref:u},null,512)],512))}},[["__scopeId","data-v-6406e025"]]);v.install=e=>e.component("DigitalHuman",v);const y=[a,u,v],g={install:e=>{y.forEach(t=>e.use(t))}};e.DemoButton=a,e.DemoInput=u,e.DigitalHuman=v,e.default=g,Object.defineProperties(e,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});