ruiyun-human 1.0.1 → 1.0.3

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,895 @@
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) / 2;
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
+ frameIndex.value = 1;
461
+ animationState.value = "standby";
462
+ };
463
+ const runAnimation = (state) => {
464
+ stop();
465
+ animationState.value = state;
466
+ loopDirection.value = 1;
467
+ let currentFrames;
468
+ let interval;
469
+ let loopConfig = null;
470
+ switch (state) {
471
+ case "standby":
472
+ currentFrames = frames.value.standby;
473
+ interval = currentHuman.value.standby.interval;
474
+ loopConfig = { type: "pingpong", next: "standby" };
475
+ break;
476
+ case "speak":
477
+ currentFrames = frames.value.speakStart;
478
+ interval = currentHuman.value.speak.interval;
479
+ loopConfig = { type: "once", next: "speakLoop" };
480
+ break;
481
+ case "speakLoop":
482
+ currentFrames = frames.value.speakLoop;
483
+ interval = currentHuman.value.speak.interval;
484
+ loopConfig = { type: "pingpong", next: "speakLoop" };
485
+ break;
486
+ case "speakEnd":
487
+ currentFrames = frames.value.speakEnd;
488
+ interval = currentHuman.value.speak.interval;
489
+ loopConfig = { type: "once", next: "standby" };
490
+ break;
491
+ default:
492
+ return;
493
+ }
494
+ const updateFrame = () => {
495
+ if (!loopConfig) {
496
+ frameIndex.value = frameIndex.value >= currentFrames.length ? 1 : frameIndex.value + 1;
497
+ return false;
498
+ }
499
+ if (loopConfig.type === "once") {
500
+ frameIndex.value++;
501
+ if (frameIndex.value <= currentFrames.length) return false;
502
+ if (loopConfig.next === "standby") {
503
+ standby();
504
+ return true;
505
+ }
506
+ if (loopConfig.next === "speakLoop") {
507
+ frameIndex.value = 1;
508
+ currentFrames = frames.value.speakLoop;
509
+ loopConfig = { type: "pingpong", next: "speakLoop" };
510
+ }
511
+ return false;
512
+ }
513
+ if (loopConfig.type === "pingpong") {
514
+ frameIndex.value += loopDirection.value;
515
+ }
516
+ return false;
517
+ };
518
+ const animate = (time) => {
519
+ if (!timestamp.value) timestamp.value = time;
520
+ if (isPaused.value) {
521
+ animationId.value = requestAnimationFrame(animate);
522
+ return;
523
+ }
524
+ if (time - timestamp.value >= interval) {
525
+ if (loopConfig && loopConfig.type === "pingpong") {
526
+ const nextIndex = frameIndex.value + loopDirection.value;
527
+ if (nextIndex > currentFrames.length) {
528
+ loopDirection.value = -1;
529
+ } else if (nextIndex < 1) {
530
+ loopDirection.value = 1;
531
+ }
532
+ }
533
+ draw(currentFrames[frameIndex.value - 1]);
534
+ const shouldStop = updateFrame();
535
+ if (shouldStop) return;
536
+ timestamp.value = time;
537
+ }
538
+ animationId.value = requestAnimationFrame(animate);
539
+ };
540
+ animationId.value = requestAnimationFrame(animate);
541
+ };
542
+ const standby = () => {
543
+ runAnimation("standby");
544
+ };
545
+ const speak = () => {
546
+ runAnimation("speak");
547
+ };
548
+ const stopSpeaking = () => {
549
+ if (animationState.value === "speak" || animationState.value === "speakLoop") {
550
+ runAnimation("speakEnd");
551
+ } else {
552
+ standby();
553
+ }
554
+ };
555
+ const pause = () => {
556
+ if (isPaused.value) return;
557
+ isPaused.value = true;
558
+ pauseSnapshot.value = {
559
+ state: animationState.value,
560
+ frameIndex: frameIndex.value,
561
+ loopDirection: loopDirection.value
562
+ };
563
+ emit("paused");
564
+ };
565
+ const resume = () => {
566
+ if (!isPaused.value) return;
567
+ isPaused.value = false;
568
+ timestamp.value = null;
569
+ if (pauseSnapshot.value) {
570
+ animationState.value = pauseSnapshot.value.state;
571
+ frameIndex.value = pauseSnapshot.value.frameIndex;
572
+ loopDirection.value = pauseSnapshot.value.loopDirection;
573
+ }
574
+ emit("resumed");
575
+ };
576
+ const waitFramesLoaded = (callback) => {
577
+ let loadedCount = 0;
578
+ const allFrames = [
579
+ ...frames.value.standby,
580
+ ...frames.value.speakStart,
581
+ ...frames.value.speakLoop,
582
+ ...frames.value.speakEnd
583
+ ];
584
+ const checkLoaded = () => {
585
+ loadedCount++;
586
+ if (loadedCount >= allFrames.length) {
587
+ callback();
588
+ }
589
+ };
590
+ allFrames.forEach((img) => {
591
+ if (img.complete) {
592
+ checkLoaded();
593
+ } else {
594
+ img.onload = checkLoaded;
595
+ img.onerror = checkLoaded;
596
+ }
597
+ });
598
+ };
599
+ const init = () => {
600
+ vue.nextTick(() => {
601
+ if (!containerRef.value || !canvasRef.value) return;
602
+ if (!props.humans || props.humans.length === 0) return;
603
+ if (!currentHuman.value) {
604
+ currentHuman.value = props.humans[0];
605
+ }
606
+ const canvas = canvasRef.value;
607
+ const dpr = window.devicePixelRatio || 1;
608
+ const width = containerRef.value.clientWidth;
609
+ const height = containerRef.value.clientHeight;
610
+ canvas.width = width * dpr;
611
+ canvas.height = height * dpr;
612
+ canvas.style.width = width + "px";
613
+ canvas.style.height = height + "px";
614
+ ctx.value = canvas.getContext("2d");
615
+ ctx.value.scale(dpr, dpr);
616
+ loadFrames();
617
+ waitFramesLoaded(() => {
618
+ draw(frames.value.standby[0]);
619
+ emit("loaded", currentHuman.value);
620
+ });
621
+ });
622
+ };
623
+ const currentAudio = vue.ref(null);
624
+ const currentTtsRequestId = vue.ref(null);
625
+ const playTTS = async (text) => {
626
+ var _a, _b, _c, _d, _e, _f, _g, _h;
627
+ if (!text || !((_a = currentHuman.value) == null ? void 0 : _a.isMuted)) return;
628
+ if (currentAudio.value) {
629
+ currentAudio.value.pause();
630
+ currentAudio.value = null;
631
+ }
632
+ currentTtsRequestId.value = Date.now();
633
+ const requestId = currentTtsRequestId.value;
634
+ try {
635
+ const cleanText = text.replace(/```[\s\S]*?```/g, "").replace(/`[^`]+`/g, "").replace(/[#*_~]/g, "").replace(/\n+/g, ",").replace(/\s+/g, " ").replace(/[,。!?]{2,}/g, ",").trim();
636
+ if (!cleanText) return;
637
+ const baseUrl = baseTTSUrl;
638
+ const sessionHash = "session_" + Date.now();
639
+ let speed = ((_c = (_b = currentHuman.value) == null ? void 0 : _b.speakSet) == null ? void 0 : _c.speed) || 1;
640
+ let age = ((_e = (_d = currentHuman.value) == null ? void 0 : _d.speakSet) == null ? void 0 : _e.age) || "Young Adult / 青年";
641
+ let sex = ((_g = (_f = currentHuman.value) == null ? void 0 : _f.speakSet) == null ? void 0 : _g.sex) || "Female / 女";
642
+ const data = [cleanText, "Auto", 32, 2, true, speed, null, true, true, sex, age, "Auto", "Auto", "Auto", "Auto"];
643
+ console.log("[OmniVoice] 提交请求:", { text: cleanText, length: cleanText.length, fn_index: 1 });
644
+ const joinRes = await fetch(`${baseUrl}/gradio_api/queue/join`, {
645
+ method: "POST",
646
+ headers: { "Content-Type": "application/json" },
647
+ body: JSON.stringify({ data, session_hash: sessionHash, fn_index: 1, trigger_id: 50 })
648
+ });
649
+ const joinData = await joinRes.json();
650
+ console.log("[OmniVoice] Step1 响应:", joinData);
651
+ console.log("[OmniVoice] Step2: 轮询等待结果");
652
+ let audioUrl = "";
653
+ let maxPolls = 60;
654
+ let pollInterval = 1e3;
655
+ while (!audioUrl && maxPolls > 0) {
656
+ await new Promise((resolve) => setTimeout(resolve, pollInterval));
657
+ maxPolls--;
658
+ try {
659
+ const pollRes = await fetch(`${baseUrl}/gradio_api/queue/data?session_hash=${sessionHash}`);
660
+ const pollText = await pollRes.text();
661
+ const lines = pollText.split("\n");
662
+ for (const line of lines) {
663
+ const trimLine = line.trim();
664
+ if (!trimLine.startsWith("data: ")) continue;
665
+ try {
666
+ const json = JSON.parse(trimLine.replace("data: ", ""));
667
+ console.log("[OmniVoice] 轮询消息:", json);
668
+ if (json.msg === "process_completed" && ((_h = json.output) == null ? void 0 : _h.data)) {
669
+ const fileData = json.output.data[0];
670
+ console.log("[OmniVoice] 获取到音频:", fileData);
671
+ if (fileData == null ? void 0 : fileData.url) audioUrl = fileData.url;
672
+ else if (fileData == null ? void 0 : fileData.path) audioUrl = `${baseUrl}/gradio_api/file=${fileData.path}`;
673
+ else if (typeof fileData === "string") audioUrl = fileData.startsWith("http") ? fileData : `${baseUrl}/gradio_api/file=${fileData}`;
674
+ else if (Array.isArray(fileData) && fileData.length >= 2) {
675
+ const samplingRate = fileData[0];
676
+ const waveform = fileData[1];
677
+ console.log("[OmniVoice] 直接获取到音频数组:", { samplingRate, waveformLength: waveform == null ? void 0 : waveform.length });
678
+ if (samplingRate && waveform && Array.isArray(waveform)) {
679
+ const audioBuffer = new ArrayBuffer(waveform.length * 2);
680
+ const view = new DataView(audioBuffer);
681
+ for (let i = 0; i < waveform.length; i++) {
682
+ view.setInt16(i * 2, waveform[i], true);
683
+ }
684
+ const wavBlob = createWavBlob(audioBuffer, samplingRate, 1, 16);
685
+ const audioObjectUrl = URL.createObjectURL(wavBlob);
686
+ if (currentTtsRequestId.value !== requestId) {
687
+ URL.revokeObjectURL(audioObjectUrl);
688
+ return;
689
+ }
690
+ currentAudio.value = new Audio(audioObjectUrl);
691
+ currentAudio.value.onplaying = () => {
692
+ console.log("[OmniVoice] 音频开始播放");
693
+ speak();
694
+ };
695
+ currentAudio.value.onended = () => {
696
+ console.log("[OmniVoice] 音频播放结束");
697
+ stopSpeaking();
698
+ currentAudio.value = null;
699
+ URL.revokeObjectURL(audioObjectUrl);
700
+ };
701
+ currentAudio.value.onerror = () => {
702
+ console.error("[OmniVoice] 音频播放失败");
703
+ stopSpeaking();
704
+ currentAudio.value = null;
705
+ URL.revokeObjectURL(audioObjectUrl);
706
+ };
707
+ await currentAudio.value.play();
708
+ return;
709
+ }
710
+ }
711
+ break;
712
+ } else if (json.msg === "process_error") {
713
+ console.error("[OmniVoice] 处理错误:", json);
714
+ standby();
715
+ return;
716
+ }
717
+ } catch (e) {
718
+ console.error("[OmniVoice] 解析轮询消息失败:", e);
719
+ }
720
+ }
721
+ } catch (e) {
722
+ console.warn("[OmniVoice] 轮询失败:", e.message);
723
+ }
724
+ }
725
+ if (audioUrl) {
726
+ if (audioUrl.startsWith("/")) audioUrl = baseUrl + audioUrl;
727
+ console.log("[OmniVoice] 下载音频:", audioUrl);
728
+ if (currentTtsRequestId.value !== requestId) return;
729
+ const audioRes = await fetch(audioUrl);
730
+ const audioBlob = await audioRes.blob();
731
+ const audioObjectUrl = URL.createObjectURL(audioBlob);
732
+ currentAudio.value = new Audio(audioObjectUrl);
733
+ currentAudio.value.onplaying = () => {
734
+ console.log("[OmniVoice] 音频开始播放");
735
+ speak();
736
+ };
737
+ currentAudio.value.onended = () => {
738
+ console.log("[OmniVoice] 音频播放结束");
739
+ stopSpeaking();
740
+ currentAudio.value = null;
741
+ URL.revokeObjectURL(audioObjectUrl);
742
+ };
743
+ currentAudio.value.onerror = () => {
744
+ console.error("[OmniVoice] 音频播放失败");
745
+ stopSpeaking();
746
+ currentAudio.value = null;
747
+ URL.revokeObjectURL(audioObjectUrl);
748
+ };
749
+ await currentAudio.value.play();
750
+ } else {
751
+ console.error("[OmniVoice] 未获取到音频");
752
+ standby();
753
+ }
754
+ } catch (e) {
755
+ console.error("[OmniVoice] TTS失败:", e);
756
+ standby();
757
+ }
758
+ };
759
+ const startRecord = async () => {
760
+ try {
761
+ if (recorder2.value) recorder2.value.stop();
762
+ await recorder2.value.start();
763
+ } catch (e) {
764
+ console.error("录音启动失败:", e);
765
+ }
766
+ };
767
+ const stopRecord = async () => {
768
+ if (!recorder2.value) return;
769
+ try {
770
+ recorder2.value.stop();
771
+ const blob = recorder2.value.getWAVBlob();
772
+ if (blob.size < 1e3) {
773
+ return;
774
+ }
775
+ const text = await audioToText(blob);
776
+ console.log("audioToText:", text);
777
+ emit("audio-ready", text);
778
+ } catch (e) {
779
+ console.error("录音处理失败:", e);
780
+ }
781
+ };
782
+ const audioToText = async (blob) => {
783
+ const formData = new FormData();
784
+ formData.append("file", blob, "recorded_audio.wav");
785
+ try {
786
+ const res = await fetch(ASR_URL, {
787
+ method: "POST",
788
+ body: formData
789
+ });
790
+ const resJson = await res.json();
791
+ const text = (resJson == null ? void 0 : resJson.text) || (resJson == null ? void 0 : resJson.text);
792
+ const message = (resJson == null ? void 0 : resJson.success) || (resJson == null ? void 0 : resJson.success);
793
+ return { status: message, text };
794
+ } catch (e) {
795
+ console.error("STT失败:", e);
796
+ return { status: e, text: "" };
797
+ }
798
+ };
799
+ const createWavBlob = (audioBuffer, sampleRate, channels, bitsPerSample) => {
800
+ const bytesPerSample = bitsPerSample / 8;
801
+ const blockAlign = channels * bytesPerSample;
802
+ const dataSize = audioBuffer.byteLength;
803
+ const buffer = new ArrayBuffer(44 + dataSize);
804
+ const view = new DataView(buffer);
805
+ view.setUint8(0, 82);
806
+ view.setUint8(1, 73);
807
+ view.setUint8(2, 70);
808
+ view.setUint8(3, 70);
809
+ view.setUint32(4, 36 + dataSize, true);
810
+ view.setUint8(8, 87);
811
+ view.setUint8(9, 65);
812
+ view.setUint8(10, 86);
813
+ view.setUint8(11, 69);
814
+ view.setUint8(12, 102);
815
+ view.setUint8(13, 109);
816
+ view.setUint8(14, 116);
817
+ view.setUint8(15, 32);
818
+ view.setUint32(16, 16, true);
819
+ view.setUint16(20, 1, true);
820
+ view.setUint16(22, channels, true);
821
+ view.setUint32(24, sampleRate, true);
822
+ view.setUint32(28, sampleRate * blockAlign, true);
823
+ view.setUint16(32, blockAlign, true);
824
+ view.setUint16(34, bitsPerSample, true);
825
+ view.setUint8(36, 100);
826
+ view.setUint8(37, 97);
827
+ view.setUint8(38, 116);
828
+ view.setUint8(39, 97);
829
+ view.setUint32(40, dataSize, true);
830
+ const audioData = new Uint8Array(audioBuffer);
831
+ const destData = new Uint8Array(buffer, 44);
832
+ destData.set(audioData);
833
+ return new Blob([buffer], { type: "audio/wav" });
834
+ };
835
+ let recorder2 = vue.ref(null);
836
+ const initRecorder = () => {
837
+ console.log("initRecorder");
838
+ if (!recorder2.value) {
839
+ recorder2.value = new Recorder({
840
+ sampleBits: 16,
841
+ sampleRate: 16e3,
842
+ numChannels: 1
843
+ });
844
+ }
845
+ };
846
+ __expose({
847
+ standby,
848
+ speak,
849
+ stopSpeaking,
850
+ pause,
851
+ resume,
852
+ playTTS,
853
+ startRecord,
854
+ stopRecord
855
+ });
856
+ vue.watch(() => props.humans, (val) => {
857
+ if (val && val.length > 0 && !currentHuman.value) {
858
+ init();
859
+ }
860
+ }, { deep: true });
861
+ vue.onMounted(() => {
862
+ initRecorder();
863
+ init();
864
+ });
865
+ vue.onUnmounted(() => {
866
+ stop();
867
+ if (recorder2.value) {
868
+ recorder2.value.stop();
869
+ }
870
+ });
871
+ return (_ctx, _cache) => {
872
+ return vue.openBlock(), vue.createElementBlock("div", {
873
+ class: "digital-human",
874
+ ref_key: "containerRef",
875
+ ref: containerRef
876
+ }, [
877
+ vue.createElementVNode("canvas", {
878
+ ref_key: "canvasRef",
879
+ ref: canvasRef
880
+ }, null, 512)
881
+ ], 512);
882
+ };
883
+ }
884
+ };
885
+ const DigitalHuman = /* @__PURE__ */ _export_sfc(_sfc_main, [["__scopeId", "data-v-aae25c55"]]);
886
+ DigitalHuman.install = (app) => app.component("DigitalHuman", DigitalHuman);
887
+ const components = [DemoButton, DemoInput, DigitalHuman];
888
+ const install = (app) => {
889
+ components.forEach((comp) => app.use(comp));
890
+ };
891
+ const index = { install };
892
+ exports.DemoButton = DemoButton;
893
+ exports.DemoInput = DemoInput;
894
+ exports.DigitalHuman = DigitalHuman;
895
+ exports.default = index;
@@ -605,8 +605,8 @@ const _sfc_main = {
605
605
  const dpr = window.devicePixelRatio || 1;
606
606
  const width = containerRef.value.clientWidth;
607
607
  const height = containerRef.value.clientHeight;
608
- canvas.width = width * 3 * dpr;
609
- canvas.height = height * 3 * dpr;
608
+ canvas.width = width * dpr;
609
+ canvas.height = height * dpr;
610
610
  canvas.style.width = width + "px";
611
611
  canvas.style.height = height + "px";
612
612
  ctx.value = canvas.getContext("2d");
@@ -771,13 +771,13 @@ const _sfc_main = {
771
771
  return;
772
772
  }
773
773
  const text = await audioToText(blob);
774
+ console.log("audioToText:", text);
774
775
  emit("audio-ready", text);
775
776
  } catch (e) {
776
777
  console.error("录音处理失败:", e);
777
778
  }
778
779
  };
779
780
  const audioToText = async (blob) => {
780
- var _a;
781
781
  const formData = new FormData();
782
782
  formData.append("file", blob, "recorded_audio.wav");
783
783
  try {
@@ -785,10 +785,13 @@ const _sfc_main = {
785
785
  method: "POST",
786
786
  body: formData
787
787
  });
788
- console.log("STT结果:", res);
789
- const text = ((_a = res.data) == null ? void 0 : _a.text) || res.text;
788
+ const resJson = await res.json();
789
+ const text = (resJson == null ? void 0 : resJson.text) || (resJson == null ? void 0 : resJson.text);
790
+ const message = (resJson == null ? void 0 : resJson.success) || (resJson == null ? void 0 : resJson.success);
791
+ return { status: message, text };
790
792
  } catch (e) {
791
793
  console.error("STT失败:", e);
794
+ return { status: e, text: "" };
792
795
  }
793
796
  };
794
797
  const createWavBlob = (audioBuffer, sampleRate, channels, bitsPerSample) => {
@@ -877,7 +880,7 @@ const _sfc_main = {
877
880
  };
878
881
  }
879
882
  };
880
- const DigitalHuman = /* @__PURE__ */ _export_sfc(_sfc_main, [["__scopeId", "data-v-132811db"]]);
883
+ const DigitalHuman = /* @__PURE__ */ _export_sfc(_sfc_main, [["__scopeId", "data-v-aae25c55"]]);
881
884
  DigitalHuman.install = (app) => app.component("DigitalHuman", DigitalHuman);
882
885
  const components = [DemoButton, DemoInput, DigitalHuman];
883
886
  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-132811db]{width:100%;height:100%;display:flex;align-items:center;justify-content:center}.digital-human canvas[data-v-132811db]{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-aae25c55]{width:100%;height:100%;display:flex;align-items:center;justify-content:center}.digital-human canvas[data-v-aae25c55]{max-width:100%;max-height:100%}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ruiyun-human",
3
- "version": "1.0.1",
3
+ "version": "1.0.3",
4
4
  "type": "module",
5
5
  "description": "数字人初步实现",
6
6
  "main": "./dist/ruiyun-human.umd.js",
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=3*a*t,e.height=3*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-132811db"]]);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"}})});