-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
909 lines (792 loc) · 28.1 KB
/
index.html
File metadata and controls
909 lines (792 loc) · 28.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Web 应用云流化集成示例</title>
<style>
:root {
color-scheme: dark;
--bg: #0f172a;
--panel: #1e293b;
--border: #334155;
--text: #e2e8f0;
--muted: #94a3b8;
--accent: #38bdf8;
--ok: #4ade80;
--warn: #fbbf24;
}
* { box-sizing: border-box; }
body {
margin: 0;
font-family: "Segoe UI", sans-serif;
background: radial-gradient(circle at top, #172554, var(--bg));
color: var(--text);
min-height: 100vh;
}
.wrap {
max-width: 960px;
margin: 0 auto;
padding: 24px;
}
h1 {
margin: 0 0 8px;
font-size: 28px;
}
.subtitle {
color: var(--muted);
margin-bottom: 24px;
line-height: 1.6;
}
.grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 16px;
}
@media (max-width: 760px) {
.grid { grid-template-columns: 1fr; }
}
.panel {
background: rgba(30, 41, 59, 0.92);
border: 1px solid var(--border);
border-radius: 12px;
padding: 16px;
}
.panel h2 {
margin: 0 0 12px;
font-size: 16px;
}
.status-row {
display: flex;
align-items: center;
gap: 8px;
margin: 8px 0;
font-size: 14px;
}
.dot {
width: 10px;
height: 10px;
border-radius: 50%;
background: #64748b;
flex-shrink: 0;
}
.dot.ok { background: var(--ok); box-shadow: 0 0 8px var(--ok); }
.dot.warn { background: var(--warn); box-shadow: 0 0 8px var(--warn); }
.dot.error { background: #f87171; box-shadow: 0 0 8px #f87171; }
.status-hint {
margin: 4px 0 8px 18px;
color: var(--muted);
font-size: 12px;
line-height: 1.5;
}
.status-hint strong {
color: #fca5a5;
font-weight: 600;
}
.status-hint code {
color: var(--accent);
}
.stats {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 8px;
margin-top: 12px;
}
.stat {
background: rgba(15, 23, 42, 0.8);
border: 1px solid var(--border);
border-radius: 8px;
padding: 10px;
}
.stat-label {
color: var(--muted);
font-size: 12px;
}
.stat-value {
font-size: 18px;
margin-top: 4px;
font-variant-numeric: tabular-nums;
}
button {
border: 1px solid var(--border);
background: #0f172a;
color: var(--text);
border-radius: 8px;
padding: 8px 12px;
cursor: pointer;
}
button:hover { border-color: var(--accent); }
button:disabled {
opacity: 0.45;
cursor: not-allowed;
}
button:disabled:hover { border-color: var(--border); }
.action-btn {
border: 1px solid var(--border);
background: #0f172a;
color: var(--text);
border-radius: 8px;
padding: 8px 12px;
cursor: pointer;
user-select: none;
-webkit-user-select: none;
display: inline-block;
}
.action-btn:hover { border-color: var(--accent); }
.action-btn.is-disabled {
opacity: 0.45;
cursor: not-allowed;
pointer-events: none;
}
/* 播放按钮:仅 is-playing 时高亮,避免播放结束后 hover 仍像选中态 */
#btn-play-buffer:hover,
#btn-play-buffer:active,
#btn-play-buffer:focus {
border-color: var(--border);
background: #0f172a;
outline: none;
box-shadow: none;
}
#btn-play-buffer:not(:disabled):hover {
border-color: var(--accent);
}
#btn-play-buffer.is-playing {
border-color: var(--accent);
background: #1e293b;
}
#btn-play-buffer.is-playing:hover,
#btn-play-buffer.is-playing:active {
border-color: var(--accent);
background: #1e293b;
}
.actions {
display: flex;
gap: 8px;
flex-wrap: wrap;
margin-top: 12px;
}
#log {
height: 220px;
overflow: auto;
background: rgba(15, 23, 42, 0.8);
border: 1px solid var(--border);
border-radius: 8px;
padding: 10px;
font-family: Consolas, monospace;
font-size: 12px;
line-height: 1.5;
white-space: pre-wrap;
}
canvas {
width: 100%;
height: 180px;
border-radius: 8px;
border: 1px solid var(--border);
background: #020617;
display: block;
}
code {
background: rgba(15, 23, 42, 0.8);
padding: 1px 6px;
border-radius: 4px;
font-size: 12px;
}
ol {
margin: 0;
padding-left: 20px;
color: var(--muted);
line-height: 1.7;
font-size: 14px;
}
.playback-guard {
display: flex;
align-items: center;
gap: 6px;
font-size: 13px;
color: var(--muted);
user-select: none;
}
.playback-guard input {
margin: 0;
}
.integration-code {
margin: 12px 0 16px;
padding: 12px;
background: rgba(15, 23, 42, 0.9);
border: 1px solid var(--border);
border-radius: 8px;
overflow: auto;
font-family: Consolas, monospace;
font-size: 12px;
line-height: 1.55;
color: #cbd5e1;
white-space: pre;
}
</style>
</head>
<body tabindex="-1">
<div class="wrap">
<h1>Web 应用云流化集成示例</h1>
<p class="subtitle">
本页面演示 Web 应用在云流化环境中与客户端通信的两种方式:文本消息通道(<code>dlcaReg</code> / <code>dlcaSend</code>),
以及接收客户端共享麦克风的 PCM 音频(<code>on_mic_pcm</code>)。
将本页部署为可访问的 Web 地址,并在管理平台中配置为应用入口即可验证。
</p>
<div class="grid">
<section class="panel">
<h2>连接状态</h2>
<div class="status-row">
<span class="dot" id="dot-bridge"></span>
<span id="status-bridge">等待云流化桥接就绪...</span>
</div>
<div class="status-row">
<span class="dot" id="dot-message"></span>
<span id="status-message">消息通道未注册</span>
</div>
<div class="status-row">
<span class="dot" id="dot-mic"></span>
<span id="status-mic">麦克风音频通道未注册</span>
</div>
<div class="status-row">
<span class="dot" id="dot-capture"></span>
<span id="status-capture">客户端麦克风采集:等待检测</span>
</div>
<div class="status-hint" id="capture-hint" hidden></div>
<div class="actions">
<button id="btn-send">发送测试消息到客户端</button>
<label class="playback-guard">
<input type="checkbox" id="chk-playback-test" />
启用回放测试
</label>
<button type="button" id="btn-play-buffer" disabled>播放最近10秒</button>
<button id="btn-clear-log">清空日志</button>
</div>
</section>
<section class="panel">
<h2>麦克风音频统计</h2>
<div class="stats">
<div class="stat">
<div class="stat-label">缓存时长</div>
<div class="stat-value" id="stat-buffer">0.0s</div>
</div>
<div class="stat">
<div class="stat-label">音频格式</div>
<div class="stat-value" id="stat-format">s16le</div>
</div>
<div class="stat">
<div class="stat-label">当前音量</div>
<div class="stat-value" id="stat-level">0%</div>
</div>
<div class="stat">
<div class="stat-label">采样率</div>
<div class="stat-value" id="stat-rate">-</div>
</div>
<div class="stat">
<div class="stat-label">声道数</div>
<div class="stat-value" id="stat-channels">-</div>
</div>
<div class="stat">
<div class="stat-label">累计包数</div>
<div class="stat-value" id="stat-packets">0</div>
</div>
<div class="stat">
<div class="stat-label">累计字节</div>
<div class="stat-value" id="stat-bytes">0</div>
</div>
</div>
</section>
</div>
<section class="panel" style="margin-top: 16px;">
<h2>麦克风音量可视化</h2>
<p style="margin: 0 0 12px; color: var(--muted); font-size: 13px;">
收到 PCM 后,波形与音量条会随客户端说话实时变化;页面会滚动缓存最近 10 秒音频。
回放测试需先勾选「启用回放测试」,再点击「播放最近10秒」(避免云流化误触)。
</p>
<canvas id="demo-canvas" width="640" height="180"></canvas>
</section>
<section class="panel" style="margin-top: 16px;">
<h2>运行日志</h2>
<div id="log"></div>
</section>
<section class="panel" style="margin-top: 16px;">
<h2>接入说明</h2>
<ol>
<li>
集成 <code>dlcaReg</code> 相关代码(页面加载早期执行),示例:
<pre class="integration-code"><script>
(function () {
function initBridge() {
if (typeof dlcaReg !== 'function') return false;
dlcaReg('on_message', function (text) {
console.log('收到客户端消息:', text);
});
dlcaReg('on_mic_pcm', function (pcmBuffer, sampleRate, channelCount, sampleCount) {
var pcm = new Int16Array(pcmBuffer);
// 处理 s16le PCM 数据
});
return true;
}
if (!initBridge()) {
setInterval(function () { initBridge() && clearInterval(this); }, 500);
}
})();
</script></pre>
</li>
<li>
集成完成后部署 Web 内容,并在云流化后台配置应用入口地址;在<strong>高级设置</strong>中开启
<strong>通信插件</strong> 和 <strong>麦克风组件</strong> 两个选项。
</li>
<li>
访问时请使用 <code>https</code> 协议,默认端口为 <code>8086</code>。
后台复制出来的地址默认为 <code>http</code>,需手动改为 <code>https://主机:8086/...</code>。
</li>
<li>网页打开后,点击<strong>允许麦克风使用</strong>,然后即可调通麦克风通道。</li>
</ol>
</section>
</div>
<script>
(function () {
const logEl = document.getElementById('log');
const dotBridge = document.getElementById('dot-bridge');
const dotMessage = document.getElementById('dot-message');
const dotMic = document.getElementById('dot-mic');
const dotCapture = document.getElementById('dot-capture');
const statusBridge = document.getElementById('status-bridge');
const statusMessage = document.getElementById('status-message');
const statusMic = document.getElementById('status-mic');
const statusCapture = document.getElementById('status-capture');
const captureHint = document.getElementById('capture-hint');
const statRate = document.getElementById('stat-rate');
const statChannels = document.getElementById('stat-channels');
const statPackets = document.getElementById('stat-packets');
const statBytes = document.getElementById('stat-bytes');
const statLevel = document.getElementById('stat-level');
const statBuffer = document.getElementById('stat-buffer');
const btnPlayBuffer = document.getElementById('btn-play-buffer');
const chkPlaybackTest = document.getElementById('chk-playback-test');
const canvas = document.getElementById('demo-canvas');
const ctx = canvas.getContext('2d');
let packetCount = 0;
let byteCount = 0;
let bridgeReady = false;
let clientCaptureActive = false;
let captureWaitTimer = null;
let targetLevel = 0;
let displayLevel = 0;
let waveform = new Float32Array(128);
let playbackContext = null;
let playbackSource = null;
let isPlaybackActive = false;
const BUFFER_SECONDS = 10;
const CAPTURE_WAIT_MS = 15000;
const CLIENT_HTTPS_HINT = '请使用 <code>https://主机:8086/...</code> 访问客户端;' +
'后台复制的地址默认为 http,需改为 https。打开页面后请允许麦克风使用。';
function log(message) {
const line = '[' + new Date().toLocaleTimeString() + '] ' + message;
logEl.textContent += line + '\n';
logEl.scrollTop = logEl.scrollHeight;
console.log(line);
}
function setStatus(dot, textEl, state, text) {
dot.className = 'dot';
if (state === 'ok') dot.classList.add('ok');
else if (state === 'warn') dot.classList.add('warn');
else if (state === 'error') dot.classList.add('error');
textEl.textContent = text;
}
function showCaptureHint(html, visible) {
captureHint.hidden = !visible;
captureHint.innerHTML = html;
}
function updateClientCaptureStatus(options) {
const abnormal = options && options.abnormal;
if (!bridgeReady) {
setStatus(dotCapture, statusCapture, 'pending', '客户端麦克风采集:等待云流化就绪');
showCaptureHint('', false);
return;
}
if (clientCaptureActive) {
setStatus(dotCapture, statusCapture, 'ok',
'客户端麦克风采集正常(已收到音频数据)');
showCaptureHint('', false);
return;
}
if (abnormal) {
setStatus(dotCapture, statusCapture, 'error',
'客户端麦克风采集异常(未收到数据)');
showCaptureHint(
'<strong>采集异常</strong>:长时间未收到麦克风 PCM。' +
'请确认已允许麦克风使用,并使用 HTTPS(端口 8086)访问。' + CLIENT_HTTPS_HINT,
true
);
return;
}
setStatus(dotCapture, statusCapture, 'warn',
'客户端麦克风采集:等待数据中...');
showCaptureHint(
'已就绪,请使用 HTTPS 打开客户端页面并允许麦克风使用。' + CLIENT_HTTPS_HINT,
true
);
}
function markClientCaptureActive() {
if (clientCaptureActive) {
return;
}
clientCaptureActive = true;
if (captureWaitTimer) {
clearTimeout(captureWaitTimer);
captureWaitTimer = null;
}
updateClientCaptureStatus();
}
function startCaptureWaitTimer() {
if (captureWaitTimer) {
clearTimeout(captureWaitTimer);
}
captureWaitTimer = setTimeout(function () {
if (!clientCaptureActive) {
updateClientCaptureStatus({ abnormal: true });
log('警告:超时未收到客户端麦克风数据,请确认已用 https://主机:8086 访问并允许麦克风');
}
}, CAPTURE_WAIT_MS);
}
class PcmHistoryBuffer {
constructor(maxSeconds) {
this.maxSeconds = maxSeconds;
this.chunks = [];
this.sampleRate = 0;
this.channelCount = 0;
this.totalSamples = 0;
}
reset() {
this.chunks = [];
this.totalSamples = 0;
}
push(pcmBuffer, sampleRate, channelCount, sampleCount) {
if (sampleCount <= 0 && pcmBuffer.byteLength > 0) {
sampleCount = pcmBuffer.byteLength / 2;
}
if (sampleCount <= 0) {
return;
}
if (this.sampleRate &&
(this.sampleRate !== sampleRate || this.channelCount !== channelCount)) {
this.reset();
}
this.sampleRate = sampleRate;
this.channelCount = channelCount;
const int16 = new Int16Array(pcmBuffer, 0, sampleCount);
this.chunks.push(new Int16Array(int16));
this.totalSamples += int16.length;
const maxSamples = this.maxSeconds * sampleRate * channelCount;
while (this.totalSamples > maxSamples && this.chunks.length > 0) {
const removed = this.chunks.shift();
this.totalSamples -= removed.length;
}
}
getBufferedSeconds() {
if (!this.sampleRate || !this.channelCount || this.totalSamples <= 0) {
return 0;
}
return this.totalSamples / (this.sampleRate * this.channelCount);
}
hasData() {
return this.totalSamples > 0 && this.sampleRate > 0 && this.channelCount > 0;
}
buildMergedPcm() {
if (!this.hasData()) {
return null;
}
const merged = new Int16Array(this.totalSamples);
let offset = 0;
for (let i = 0; i < this.chunks.length; i++) {
merged.set(this.chunks[i], offset);
offset += this.chunks[i].length;
}
return merged;
}
}
const pcmHistory = new PcmHistoryBuffer(BUFFER_SECONDS);
function updateBufferUi() {
const seconds = pcmHistory.getBufferedSeconds();
statBuffer.textContent = seconds.toFixed(1) + 's';
const canPlay = seconds >= 0.1 && chkPlaybackTest.checked && !isPlaybackActive;
btnPlayBuffer.disabled = !canPlay;
}
function setPlayBufferPlaying(playing) {
if (playing) {
btnPlayBuffer.classList.add('is-playing');
btnPlayBuffer.textContent = '播放中...';
btnPlayBuffer.disabled = true;
} else {
btnPlayBuffer.classList.remove('is-playing');
btnPlayBuffer.textContent = '播放最近10秒';
updateBufferUi();
}
}
function stopPlayback() {
if (!playbackSource) {
return;
}
const source = playbackSource;
playbackSource = null;
try {
source.stop();
} catch (e) {
// ignore if already stopped
}
try {
source.disconnect();
} catch (e) {
// ignore
}
}
function closePlaybackContext() {
stopPlayback();
if (!playbackContext) {
return;
}
try {
playbackContext.close();
} catch (e) {
// ignore
}
playbackContext = null;
}
// 须在用户点击的同步调用栈内创建 AudioContext;CEF 下 resume() 常无声
function primePlaybackContext() {
closePlaybackContext();
playbackContext = new (window.AudioContext || window.webkitAudioContext)();
}
function finishPlayback(source) {
if (playbackSource !== source) {
return;
}
playbackSource = null;
isPlaybackActive = false;
setPlayBufferPlaying(false);
}
function playRecentBuffer() {
if (isPlaybackActive) {
return;
}
if (!pcmHistory.hasData()) {
log('缓存为空,无法播放');
return;
}
isPlaybackActive = true;
setPlayBufferPlaying(true);
try {
if (!playbackContext) {
log('AudioContext 未就绪,请重新点击播放');
return;
}
const merged = pcmHistory.buildMergedPcm();
if (!merged) {
log('缓存为空,无法播放');
return;
}
const sampleRate = pcmHistory.sampleRate;
const channelCount = pcmHistory.channelCount;
const frames = Math.floor(merged.length / channelCount);
if (frames <= 0) {
log('缓存数据无效,无法播放');
return;
}
stopPlayback();
const audioBuffer = playbackContext.createBuffer(channelCount, frames, sampleRate);
for (let ch = 0; ch < channelCount; ch++) {
const channelData = audioBuffer.getChannelData(ch);
for (let i = 0; i < frames; i++) {
channelData[i] = merged[i * channelCount + ch] / 32768;
}
}
const source = playbackContext.createBufferSource();
source.buffer = audioBuffer;
source.connect(playbackContext.destination);
source.onended = function () {
finishPlayback(source);
};
playbackSource = source;
const duration = pcmHistory.getBufferedSeconds();
source.start(0);
log('开始播放缓存音频: ' + duration.toFixed(1) + 's, ' +
sampleRate + 'Hz, ' + channelCount + ' 声道, ctx=' + playbackContext.state);
} catch (err) {
stopPlayback();
isPlaybackActive = false;
setPlayBufferPlaying(false);
log('播放失败: ' + err.message);
} finally {
if (isPlaybackActive && !playbackSource) {
stopPlayback();
isPlaybackActive = false;
setPlayBufferPlaying(false);
}
}
}
function analyzePcm(pcmBuffer, sampleCount) {
const int16 = new Int16Array(pcmBuffer);
const count = sampleCount > 0 ? Math.min(sampleCount, int16.length) : int16.length;
if (count <= 0) {
return;
}
let sumSquares = 0;
for (let i = 0; i < count; i++) {
const sample = int16[i] / 32768;
sumSquares += sample * sample;
}
const rms = Math.sqrt(sumSquares / count);
targetLevel = Math.min(100, Math.round(rms * 500));
const barCount = waveform.length;
const step = Math.max(1, Math.floor(count / barCount));
for (let i = 0; i < barCount; i++) {
const index = Math.min(i * step, count - 1);
waveform[i] = int16[index] / 32768;
}
}
function drawDemoFrame() {
const w = canvas.width;
const h = canvas.height;
displayLevel += (targetLevel - displayLevel) * 0.25;
statLevel.textContent = Math.round(displayLevel) + '%';
const gradient = ctx.createLinearGradient(0, 0, w, h);
gradient.addColorStop(0, '#0f172a');
gradient.addColorStop(1, '#1e1b4b');
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, w, h);
const meterW = w - 40;
const meterH = 14;
const meterX = 20;
const meterY = 24;
ctx.fillStyle = 'rgba(255,255,255,0.12)';
ctx.fillRect(meterX, meterY, meterW, meterH);
ctx.fillStyle = displayLevel > 60 ? '#f87171' : displayLevel > 30 ? '#fbbf24' : '#4ade80';
ctx.fillRect(meterX, meterY, meterW * (displayLevel / 100), meterH);
ctx.strokeStyle = 'rgba(56, 189, 248, 0.9)';
ctx.lineWidth = 2;
ctx.beginPath();
const waveTop = 56;
const waveHeight = h - waveTop - 24;
const waveStep = (w - 40) / waveform.length;
for (let i = 0; i < waveform.length; i++) {
const x = 20 + i * waveStep;
const y = waveTop + waveHeight / 2 - waveform[i] * waveHeight * 0.45;
if (i === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
}
ctx.stroke();
ctx.fillStyle = 'rgba(255,255,255,0.08)';
ctx.fillRect(20, waveTop, w - 40, waveHeight);
ctx.fillStyle = '#e2e8f0';
ctx.font = '14px Segoe UI, sans-serif';
ctx.fillText('麦克风音量 ' + Math.round(displayLevel) + '%', 20, 16);
ctx.fillStyle = '#94a3b8';
ctx.font = '12px Segoe UI, sans-serif';
const hint = clientCaptureActive
? '对着客户端麦克风说话,观察波形变化'
: '等待客户端共享麦克风...';
ctx.fillText(hint, 20, h - 8);
if (!clientCaptureActive) {
targetLevel = Math.max(0, targetLevel - 1);
}
requestAnimationFrame(drawDemoFrame);
}
function registerBridgeCallbacks() {
if (typeof window.dlcaReg !== 'function') {
setStatus(dotBridge, statusBridge, 'warn', '当前为本地预览模式,请通过云流化会话访问');
updateClientCaptureStatus();
return false;
}
if (bridgeReady) {
return true;
}
setStatus(dotBridge, statusBridge, 'ok', '云流化桥接已就绪');
window.dlcaReg('on_message', (text) => {
log('收到客户端消息: ' + text);
});
setStatus(dotMessage, statusMessage, 'ok', '消息通道已注册');
window.dlcaReg('on_mic_pcm', (pcmBuffer, sampleRate, channelCount, sampleCount) => {
if (sampleCount <= 0 && pcmBuffer.byteLength > 0) {
sampleCount = pcmBuffer.byteLength / 2;
}
markClientCaptureActive();
packetCount += 1;
byteCount += pcmBuffer.byteLength;
statRate.textContent = String(sampleRate);
statChannels.textContent = String(channelCount);
statPackets.textContent = String(packetCount);
statBytes.textContent = String(byteCount);
analyzePcm(pcmBuffer, sampleCount);
pcmHistory.push(pcmBuffer, sampleRate, channelCount, sampleCount);
updateBufferUi();
if (packetCount === 1 || packetCount % 50 === 0) {
log('收到麦克风 PCM: bytes=' + pcmBuffer.byteLength +
', rate=' + sampleRate +
', channels=' + channelCount +
', samples=' + sampleCount);
}
});
setStatus(dotMic, statusMic, 'ok', '麦克风音频通道已注册,等待客户端麦克风数据');
bridgeReady = true;
log('桥接接口注册完成');
updateClientCaptureStatus();
startCaptureWaitTimer();
return true;
}
document.querySelectorAll('.actions button').forEach(function (btn) {
if (btn.id === 'btn-play-buffer') {
return;
}
btn.addEventListener('mousedown', function (e) {
if (!btn.disabled) {
e.preventDefault();
}
});
});
document.getElementById('btn-send').addEventListener('click', function () {
if (typeof window.dlcaSend !== 'function') {
log('当前环境不支持 dlcaSend');
return;
}
const payload = 'hello from web app ' + new Date().toISOString();
window.dlcaSend(payload);
log('已发送到客户端: ' + payload);
});
document.getElementById('btn-play-buffer').addEventListener('click', function () {
if (btnPlayBuffer.disabled || isPlaybackActive) {
return;
}
if (!chkPlaybackTest.checked) {
log('请先勾选「启用回放测试」');
return;
}
primePlaybackContext();
playRecentBuffer();
});
chkPlaybackTest.addEventListener('change', function () {
if (!chkPlaybackTest.checked) {
closePlaybackContext();
isPlaybackActive = false;
setPlayBufferPlaying(false);
}
updateBufferUi();
});
document.getElementById('btn-clear-log').addEventListener('click', function () {
logEl.textContent = '';
});
drawDemoFrame();
updateClientCaptureStatus();
updateBufferUi();
if (!registerBridgeCallbacks()) {
const timer = setInterval(function () {
if (registerBridgeCallbacks()) {
clearInterval(timer);
}
}, 500);
}
log('示例页面已加载。请通过管理平台配置应用入口,并从客户端进入云流化会话进行验证。');
})();
</script>
</body>
</html>