Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
1348 lines (1160 loc) · 45.7 KB
/
Copy pathindex.js
File metadata and controls
1348 lines (1160 loc) · 45.7 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
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 导入 CameraManager
import CameraManager from './camera-manager.js';
// 数据库相关变量
let db = null;
const DB_NAME = 'FingerExerciseDB';
const STORE_NAME = 'recordings';
const DB_VERSION = 1;
// 获取摄像头管理器实例
const cameraManager = CameraManager.getInstance();
// 流媒体相关变量
let streamingRecorder = null;
let streamInterval = null;
// 初始化 IndexedDB
async function initDB() {
return new Promise((resolve, reject) => {
const request = indexedDB.open(DB_NAME, DB_VERSION);
request.onerror = () => reject(request.error);
request.onsuccess = () => {
db = request.result;
resolve();
};
request.onupgradeneeded = (event) => {
const db = event.target.result;
if (!db.objectStoreNames.contains(STORE_NAME)) {
db.createObjectStore(STORE_NAME, { keyPath: 'id' });
}
};
});
}
// 保存录制视频到 IndexedDB
async function saveRecording(blob, metadata) {
if (!db) await initDB();
return new Promise((resolve, reject) => {
const transaction = db.transaction([STORE_NAME], 'readwrite');
const store = transaction.objectStore(STORE_NAME);
transaction.oncomplete = () => resolve();
transaction.onerror = () => reject(transaction.error);
const reader = new FileReader();
reader.onload = () => {
const recording = {
id: metadata.id,
data: reader.result,
metadata: metadata,
timestamp: new Date().getTime()
};
try {
store.put(recording);
} catch (error) {
reject(error);
}
};
reader.onerror = () => reject(reader.error);
reader.readAsArrayBuffer(blob);
});
}
// 从 IndexedDB 获取录制的视频
async function getRecording(id) {
if (!db) await initDB();
return new Promise((resolve, reject) => {
const transaction = db.transaction([STORE_NAME], 'readonly');
const store = transaction.objectStore(STORE_NAME);
transaction.oncomplete = () => {
if (request.result) {
const blob = new Blob([request.result.data], { type: 'video/webm' });
resolve({
blob: blob,
metadata: request.result.metadata
});
} else {
resolve(null);
}
};
transaction.onerror = () => reject(transaction.error);
const request = store.get(id);
});
}
// 获取所有录制的视频列表
async function getAllRecordings() {
if (!db) await initDB();
return new Promise((resolve, reject) => {
const transaction = db.transaction([STORE_NAME], 'readonly');
const store = transaction.objectStore(STORE_NAME);
transaction.oncomplete = () => resolve(request.result);
transaction.onerror = () => reject(transaction.error);
const request = store.getAll();
});
}
// 删除录制的视频
async function deleteRecording(id) {
if (!db) await initDB();
return new Promise((resolve, reject) => {
const transaction = db.transaction([STORE_NAME], 'readwrite');
const store = transaction.objectStore(STORE_NAME);
transaction.oncomplete = () => resolve();
transaction.onerror = () => reject(transaction.error);
store.delete(id);
});
}
// 开始流媒体传输
async function startStreaming() {
try {
const stream = cameraManager.getStream();
if (!stream) {
throw new Error('没有可用的摄像头流');
}
// 创建 MediaRecorder 实例
const options = {
mimeType: cameraManager.getBestRecordingFormat(),
videoBitsPerSecond: 1000000,
audioBitsPerSecond: 128000
};
streamingRecorder = new MediaRecorder(stream, options);
const chunks = [];
streamingRecorder.ondataavailable = (e) => {
if (e.data.size > 0) {
chunks.push(e.data);
}
};
streamingRecorder.onstop = async () => {
const blob = new Blob(chunks, { type: options.mimeType });
// 这里可以添加将视频数据发送到服务器的代码
console.log('流媒体数据已收集,大小:', blob.size);
};
// 每5秒收集一次数据
streamingRecorder.start(5000);
streamInterval = setInterval(() => {
if (streamingRecorder && streamingRecorder.state === 'recording') {
streamingRecorder.requestData();
}
}, 5000);
return {
success: true,
message: '流媒体传输已开始'
};
} catch (error) {
console.error('开始流媒体传输失败:', error);
return {
success: false,
message: `流媒体传输失败: ${error.message}`
};
}
}
// 停止流媒体传输
function stopStreaming() {
if (streamingRecorder && streamingRecorder.state === 'recording') {
streamingRecorder.stop();
}
if (streamInterval) {
clearInterval(streamInterval);
streamInterval = null;
}
streamingRecorder = null;
}
// 流程控制器类
class ExerciseFlowController {
constructor() {
this.events = {};
this.currentState = {
exerciseId: null,
episodeId: null,
isCameraReady: false,
isVideoLoaded: false,
isPreviewPlayed: false,
isRecording: false,
scores: [],
averageScore: null
};
// 初始化事件
this.initEvents();
}
// 初始化事件系统
initEvents() {
this.events = {
'cameraReady': [],
'videoLoaded': [],
'previewComplete': [],
'countdownStart': [],
'countdownComplete': [],
'recordingStart': [],
'recordingComplete': [],
'scoreReceived': [],
'exerciseComplete': []
};
}
// 事件监听器
on(eventName, callback) {
if (this.events[eventName]) {
this.events[eventName].push(callback);
}
}
// 事件触发
emit(eventName, data) {
if (this.events[eventName]) {
this.events[eventName].forEach(callback => callback(data));
}
}
// 开始练习流程
async startExercise(exerciseId, episodeId) {
this.currentState.exerciseId = exerciseId;
this.currentState.episodeId = episodeId;
this.currentState.scores = [];
try {
// 1. 检测并获取摄像头权限
await this.initializeCamera();
// 2. 加载视频
await this.loadVideo();
// 3. 播放预览
await this.playPreview();
// 4. 显示手型提示和倒计时
await this.showHandGuideAndCountdown();
// 5. 开始正式练习
await this.startPractice();
} catch (error) {
console.error('练习流程出错:', error);
this.handleError(error);
}
}
// 初始化摄像头
async initializeCamera() {
try {
const result = await cameraManager.startCamera();
if (result.success) {
this.currentState.isCameraReady = true;
// 获取摄像头元素并隐藏
const cameraElement = document.getElementById('cameraElement');
cameraElement.style.cssText = `
width: 100%;
height: 100%;
object-fit: cover;
background-color: #F5F5DC;
display: none;
`;
cameraElement.srcObject = result.stream;
this.emit('cameraReady', { stream: result.stream });
} else {
throw new Error(result.message);
}
} catch (error) {
throw new Error(`摄像头初始化失败: ${error.message}`);
}
}
// 加载视频
async loadVideo() {
return new Promise((resolve, reject) => {
const video = document.getElementById('exercise-video');
video.src = `video/shouzhicao_${this.currentState.exerciseId}/${this.currentState.exerciseId}_${this.currentState.episodeId}.mp4`;
const timeout = setTimeout(() => {
reject(new Error('视频加载超时'));
}, 10000);
video.onloadeddata = () => {
clearTimeout(timeout);
this.currentState.isVideoLoaded = true;
this.emit('videoLoaded', { video });
resolve();
};
video.onerror = () => {
clearTimeout(timeout);
reject(new Error(`无法加载视频: ${video.src}`));
};
});
}
// 播放预览
async playPreview() {
return new Promise((resolve) => {
const video = document.getElementById('exercise-video');
video.currentTime = 0;
video.play();
const checkTime = () => {
if (video.currentTime >= 10) {
video.pause();
this.currentState.isPreviewPlayed = true;
// 显示摄像头画面
const cameraElement = document.getElementById('cameraElement');
cameraElement.style.display = 'block';
this.emit('previewComplete');
resolve();
} else {
requestAnimationFrame(checkTime);
}
};
checkTime();
});
}
// 显示手型提示和倒计时
async showHandGuideAndCountdown() {
// 显示手型提示
const handGuideOverlay = document.querySelector('.hand-guide-overlay');
const countdownOverlay = document.querySelector('.countdown-overlay');
const countdownNumber = document.querySelector('.countdown-number');
// 显示手型提示
handGuideOverlay.style.display = 'block';
this.emit('countdownStart');
return new Promise((resolve) => {
let count = 3;
// 显示倒计时遮罩
countdownOverlay.style.display = 'flex';
countdownNumber.textContent = count;
const countdownInterval = setInterval(() => {
if (count > 0) {
this.emit('countdownTick', { count });
countdownNumber.textContent = count;
count--;
} else {
clearInterval(countdownInterval);
// 隐藏倒计时和手型提示
countdownOverlay.style.display = 'none';
handGuideOverlay.style.display = 'none';
this.emit('countdownComplete');
resolve();
}
}, 1000);
});
}
// 开始正式练习
async startPractice() {
const video = document.getElementById('exercise-video');
// 设置背景色和过渡效果
document.body.style.cssText = `
background-color: #F5F5DC;
transition: background-color 0.5s ease;
`;
// 调整摄像头画面容器样式
const cameraContainer = document.getElementById('cameraElement').parentElement;
cameraContainer.style.cssText = `
width: 100%;
height: 100%;
background-color: #F5F5DC;
display: flex;
justify-content: center;
align-items: center;
overflow: hidden;
position: relative;
transition: all 0.5s ease;
`;
// 调整摄像头画面样式
const cameraElement = document.getElementById('cameraElement');
cameraElement.style.cssText = `
width: 100%;
height: 100%;
object-fit: cover;
background-color: #F5F5DC;
transition: all 0.5s ease;
filter: brightness(1.05) contrast(1.05);
`;
// 创建练习状态提示
const practiceStatus = document.createElement('div');
practiceStatus.style.cssText = `
position: fixed;
top: 20px;
left: 50%;
transform: translateX(-50%);
background-color: rgba(255, 255, 255, 0.9);
padding: 10px 20px;
border-radius: 20px;
font-size: 16px;
color: #333;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
z-index: 1000;
opacity: 0;
transition: opacity 0.3s ease;
`;
document.body.appendChild(practiceStatus);
// 创建进度条
const progressContainer = document.createElement('div');
progressContainer.style.cssText = `
position: fixed;
bottom: 40px;
left: 50%;
transform: translateX(-50%);
width: 800px;
height: 80px;
display: none;
z-index: 1000;
opacity: 0;
transition: opacity 0.5s ease;
`;
// 创建进度文本
const progressText = document.createElement('div');
progressText.style.cssText = `
text-align: right;
margin-bottom: 5px;
font-size: 18px;
color: #333;
font-weight: 500;
text-shadow: 0 1px 2px rgba(0,0,0,0.1);
`;
progressContainer.appendChild(progressText);
// 创建进度条背景
const progressBar = document.createElement('div');
progressBar.style.cssText = `
width: 100%;
height: 20px;
background-color: #E3F2FD;
border-radius: 10px;
overflow: hidden;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
position: relative;
`;
// 创建进度条填充
const progressFill = document.createElement('div');
progressFill.style.cssText = `
width: 0%;
height: 100%;
background: linear-gradient(90deg, #2196F3, #64B5F6);
transition: width 0.3s ease;
box-shadow: 0 2px 4px rgba(33,150,243,0.3);
position: relative;
overflow: hidden;
`;
// 添加进度条动画效果
const progressAnimation = document.createElement('div');
progressAnimation.style.cssText = `
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: linear-gradient(
90deg,
rgba(255,255,255,0) 0%,
rgba(255,255,255,0.3) 50%,
rgba(255,255,255,0) 100%
);
animation: progressShine 2s infinite;
`;
progressFill.appendChild(progressAnimation);
progressBar.appendChild(progressFill);
progressContainer.appendChild(progressBar);
document.body.appendChild(progressContainer);
// 添加进度条动画样式
const style = document.createElement('style');
style.textContent = `
@keyframes progressShine {
0% { transform: translateX(-100%); }
100% { transform: translateX(100%); }
}
`;
document.head.appendChild(style);
// 计算视频实际时长(减去10秒预览)
const actualDuration = video.duration - 10;
// 更新进度条函数
const updateProgress = () => {
const currentTime = video.currentTime - 10; // 减去预览时间
if (currentTime < 0) return;
// 计算进度(1-4)
const progress = Math.min(4, Math.ceil((currentTime / actualDuration) * 4));
const percentage = (currentTime / actualDuration) * 100;
// 更新进度条
progressFill.style.width = `${percentage}%`;
progressText.textContent = `${progress}/4`;
// 更新状态提示
practiceStatus.textContent = `正在练习中... (${progress}/4)`;
practiceStatus.style.opacity = '1';
};
// 开始播放视频
video.play();
// 显示进度条(带动画)
progressContainer.style.display = 'block';
setTimeout(() => {
progressContainer.style.opacity = '1';
}, 100);
// 监听视频播放进度
video.addEventListener('timeupdate', updateProgress);
// 开始录制循环
this.startRecordingLoop();
// 监听视频结束
video.onended = () => {
// 淡出进度条和状态提示
progressContainer.style.opacity = '0';
practiceStatus.style.opacity = '0';
// 延迟移除元素
setTimeout(() => {
document.body.removeChild(progressContainer);
document.body.removeChild(practiceStatus);
}, 500);
// 移除事件监听
video.removeEventListener('timeupdate', updateProgress);
this.stopRecordingLoop();
this.calculateAverageScore();
this.emit('exerciseComplete', {
scores: this.currentState.scores,
averageScore: this.currentState.averageScore
});
};
}
// 录制循环
async startRecordingLoop() {
this.currentState.isRecording = true;
while (this.currentState.isRecording) {
try {
const result = await cameraManager.startRecording();
if (result.success) {
this.emit('recordingStart');
// 等待5秒
await new Promise(resolve => setTimeout(resolve, 5000));
const stopResult = await cameraManager.stopRecording();
if (stopResult.success) {
// 发送到服务器并获取分数
const score = await this.sendRecordingToServer(stopResult.blob);
this.currentState.scores.push(score);
this.emit('scoreReceived', { score });
}
}
} catch (error) {
console.error('录制循环出错:', error);
this.emit('recordingError', { error });
}
}
}
// 停止录制循环
stopRecordingLoop() {
this.currentState.isRecording = false;
}
// 发送录制到服务器
async sendRecordingToServer(blob) {
const formData = new FormData();
formData.append('file', blob, `recording_${this.currentState.exerciseId}_${this.currentState.episodeId}.mp4`);
formData.append('exercise_id', this.currentState.exerciseId);
formData.append('episode_id', this.currentState.episodeId);
formData.append('timestamp', Date.now());
formData.append('duration', '5');
formData.append('is_streaming', 'false');
try {
// 使用代理服务器地址
const response = await fetch('http://127.0.0.1:9000/api/evaluate_finger_exercise', {
method: 'POST',
body: formData
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const result = await response.json();
if (result.status === 1) {
return result.data.score;
} else {
throw new Error(result.message || '评估失败');
}
} catch (error) {
console.error('发送录制失败:', error);
// 返回一个默认分数,避免流程中断
return 60;
}
}
// 计算平均分
calculateAverageScore() {
if (this.currentState.scores.length > 0) {
this.currentState.averageScore = Math.round(
this.currentState.scores.reduce((sum, score) => sum + score, 0) /
this.currentState.scores.length
);
}
}
// 错误处理
handleError(error) {
console.error('流程错误:', error);
// 可以在这里添加错误提示UI
}
}
// 创建流程控制器实例
const flowController = new ExerciseFlowController();
// 修改startPractice函数,使用流程控制器
async function startPractice(exerciseId, episodeId) {
// 显示练习页面
document.querySelector('.exercise-list').style.display = 'none';
document.querySelector('.episode-selection').style.display = 'none';
document.querySelector('.exercise-practice').style.display = 'flex';
// 使用流程控制器开始练习
await flowController.startExercise(exerciseId, episodeId);
}
// 添加事件监听
flowController.on('cameraReady', ({ stream }) => {
console.log('摄像头已就绪');
});
flowController.on('videoLoaded', ({ video }) => {
console.log('视频加载完成');
});
flowController.on('previewComplete', () => {
console.log('预览播放完成,摄像头画面已显示');
});
flowController.on('countdownStart', () => {
const handGuideOverlay = document.querySelector('.hand-guide-overlay');
const countdownOverlay = document.querySelector('.countdown-overlay');
handGuideOverlay.style.display = 'block';
countdownOverlay.style.display = 'flex';
});
flowController.on('countdownTick', ({ count }) => {
const countdownNumber = document.querySelector('.countdown-number');
countdownNumber.textContent = count;
});
flowController.on('countdownComplete', () => {
const handGuideOverlay = document.querySelector('.hand-guide-overlay');
const countdownOverlay = document.querySelector('.countdown-overlay');
handGuideOverlay.style.display = 'none';
countdownOverlay.style.display = 'none';
});
flowController.on('recordingStart', () => {
console.log('开始录制');
});
flowController.on('scoreReceived', ({ score }) => {
console.log('收到分数:', score);
});
flowController.on('exerciseComplete', ({ scores, averageScore }) => {
console.log('练习完成,平均分:', averageScore);
// 显示练习总结
showExerciseSummary();
});
// 显示练习总结
function showExerciseSummary() {
// 创建总结弹窗
const summaryOverlay = document.createElement('div');
summaryOverlay.className = 'summary-overlay';
summaryOverlay.style.cssText = `
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.8);
display: flex;
justify-content: center;
align-items: center;
z-index: 1000;
`;
// 创建总结内容
const summaryContent = document.createElement('div');
summaryContent.className = 'summary-content';
summaryContent.style.cssText = `
background: white;
padding: 20px;
border-radius: 10px;
max-width: 80%;
max-height: 80%;
overflow-y: auto;
`;
// 获取所有节的分数
const scores = flowController.currentState.scores;
const averageScore = flowController.currentState.averageScore;
// 生成总结HTML
summaryContent.innerHTML = `
<h2 style="text-align: center; margin-bottom: 20px;">练习总结</h2>
<div style="margin-bottom: 20px;">
<h3>第${flowController.currentState.episodeId}节练习</h3>
<p>总评分次数: ${scores.length}</p>
<p>平均分数: ${averageScore}分</p>
<div style="margin-top: 10px;">
<h4>详细分数:</h4>
<ul style="list-style: none; padding: 0;">
${scores.map((score, index) => `
<li style="margin: 5px 0;">第${index + 1}次评分: ${score}分</li>
`).join('')}
</ul>
</div>
</div>
<div style="text-align: center;">
<button id="closeSummary" style="
padding: 10px 20px;
background: #4CAF50;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
">关闭</button>
</div>
`;
// 添加到页面
summaryOverlay.appendChild(summaryContent);
document.body.appendChild(summaryOverlay);
// 添加关闭按钮事件
document.getElementById('closeSummary').onclick = () => {
document.body.removeChild(summaryOverlay);
// 返回选集页面
document.querySelector('.exercise-practice').style.display = 'none';
document.querySelector('.episode-selection').style.display = 'flex';
};
}
// 导出所有需要的函数
export {
initDB,
saveRecording,
getRecording,
getAllRecordings,
deleteRecording,
startStreaming,
stopStreaming
};
// 页面加载时的初始化
document.addEventListener('DOMContentLoaded', function() {
// 初始化数据库
initDB();
// 自适应缩放
function resize() {
const container = document.querySelector('.container');
const windowWidth = window.innerWidth;
const windowHeight = window.innerHeight;
const scaleX = windowWidth / 1080;
const scaleY = windowHeight / 1920;
const scale = Math.min(scaleX, scaleY);
const scaledWidth = 1080 * scale;
const scaledHeight = 1920 * scale;
const translateX = (windowWidth - scaledWidth) / 2;
const translateY = (windowHeight - scaledHeight) / 2;
container.style.transform = `translate(${translateX}px, ${translateY}px) scale(${scale})`;
container.style.position = 'absolute';
container.style.left = '50%';
container.style.top = '50%';
container.style.transform = `translate(-50%, -50%) scale(${scale})`;
}
// 初始化和窗口大小改变时调整
resize();
window.addEventListener('resize', resize);
window.addEventListener('orientationchange', resize);
// 防止iOS橡皮筋效果
document.body.addEventListener('touchmove', function(e) {
if (e.target.closest('.episode-list') === null) {
e.preventDefault();
}
}, { passive: false });
// DOM元素引用
const exerciseCards = document.querySelectorAll('.exercise-card');
const exerciseList = document.querySelector('.exercise-list');
const episodeSelection = document.querySelector('.episode-selection');
const exercisePractice = document.querySelector('.exercise-practice');
const backBtn = document.querySelector('.back-btn');
const listBackBtn = document.querySelector('.list-back-btn');
const startPracticeBtn = document.getElementById('startPracticeBtn');
const countdownOverlay = document.querySelector('.countdown-overlay');
const countdownNumber = document.querySelector('.countdown-number');
const cameraElement = document.getElementById('cameraElement');
const startCameraBtn = document.getElementById('startCameraBtn');
const stopCameraBtn = document.getElementById('stopCameraBtn');
const startRecordBtn = document.getElementById('startRecordBtn');
const stopRecordBtn = document.getElementById('stopRecordBtn');
const startStreamBtn = document.getElementById('startStreamBtn');
const stopStreamBtn = document.getElementById('stopStreamBtn');
const recordingTime = document.querySelector('.recording-time');
const practiceStatus = document.querySelector('.practice-status');
// 全局状态变量
let currentExerciseId = null;
let currentEpisodeId = null;
let nextEpisodeId = null;
let cameraStream = null;
let streamingRecorder = null;
let countdownTimer = null;
let recordingTimer = null;
let recordingAnimationFrame = null;
let mediaRecorder = null;
let recordedChunks = [];
let recordingStartTime = null;
let currentEpisodeScores = []; // 当前节的分数缓存
let episodeAverageScores = {}; // 各节的平均分记录
// 调试控制开关
const DEBUG_MODE = true; // 设为false可关闭调试功能
let debugFileCounter = 0; // 调试文件计数器
// 清理所有计时器的函数
function clearAllTimers() {
if (countdownTimer) {
clearInterval(countdownTimer);
countdownTimer = null;
}
if (recordingTimer) {
clearInterval(recordingTimer);
recordingTimer = null;
}
if (recordingAnimationFrame) {
cancelAnimationFrame(recordingAnimationFrame);
recordingAnimationFrame = null;
}
}
// 调试日志函数
function debugLog(...args) {
if (DEBUG_MODE) {
console.log('[DEBUG]', ...args);
}
}
// 更新录制时间显示
function updateRecordingTime() {
if (!recordingStartTime) return;
const elapsed = Math.floor((Date.now() - recordingStartTime) / 1000);
const minutes = Math.floor(elapsed / 60).toString().padStart(2, '0');
const seconds = (elapsed % 60).toString().padStart(2, '0');
recordingTime.textContent = `${minutes}:${seconds}`;
}
// 保存节平均分到localStorage
function saveEpisodeScore(exerciseId, episodeId, averageScore) {
const key = `${exerciseId}_${episodeId}`;
episodeAverageScores[key] = averageScore;
// 同时保存到localStorage
try {
localStorage.setItem('episodeAverageScores', JSON.stringify(episodeAverageScores));
console.log(`节 ${exerciseId}-${episodeId} 平均分已保存: ${averageScore}`);
} catch (error) {
console.error('保存平均分失败:', error);
}
}
// 从localStorage加载历史平均分
function loadEpisodeScores() {
try {
const saved = localStorage.getItem('episodeAverageScores');
if (saved) {
episodeAverageScores = JSON.parse(saved);
console.log('已加载历史平均分:', episodeAverageScores);
}
} catch (error) {
console.error('加载历史平均分失败:', error);
episodeAverageScores = {};
}
}
// 下载文件(重新启用)
async function downloadFile(blob, filename) {
try {
debugLog(`开始下载文件: ${filename}, 大小: ${blob.size} bytes`);
// 创建下载链接
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
a.style.display = 'none';
// 添加到DOM并触发下载
document.body.appendChild(a);
a.click();
// 清理
document.body.removeChild(a);
URL.revokeObjectURL(url);
console.log(`文件下载已触发: ${filename}`);
debugLog(`文件下载完成: ${filename}`);
return true;
} catch (error) {
console.error('下载文件失败:', error);
debugLog('下载文件失败:', error);
return false;
}
}
// 获取最佳录制格式(优先MP4,参照camera-debug.html)
function getBestRecordingFormat() {
const preferredFormats = [
'video/mp4; codecs="avc1.42E01E"',
'video/mp4; codecs="avc1.42001E"',
'video/mp4',
'video/webm; codecs="vp8"',
'video/webm; codecs="vp9"',
'video/webm'
];
for (const format of preferredFormats) {
if (MediaRecorder.isTypeSupported(format)) {
debugLog('选择的录制格式:', format);
return format;
}
}
return null;
}
// 验证视频文件(针对短片段优化)
async function validateVideo(blob, isShortSegment = false) {
return new Promise((resolve) => {
const video = document.createElement('video');
const url = URL.createObjectURL(blob);
let isValid = false;
let validationComplete = false;
// 短片段使用更短的超时时间
const timeoutDuration = isShortSegment ? 3000 : 5000;
const timeout = setTimeout(() => {
if (!validationComplete) {
validationComplete = true;
cleanup();