Spaces:
Sleeping

File size: 28,540 Bytes
56ddde3
 
 
 
b05ee35
 
56ddde3
b05ee35
 
56ddde3
b05ee35
56ddde3
b05ee35
56ddde3
 
 
 
b05ee35
 
 
 
56ddde3
 
b05ee35
 
 
 
56ddde3
 
 
b05ee35
56ddde3
 
 
 
b05ee35
 
56ddde3
 
b05ee35
56ddde3
 
b05ee35
56ddde3
 
b05ee35
56ddde3
 
b05ee35
 
56ddde3
 
b05ee35
 
 
 
 
56ddde3
 
b05ee35
56ddde3
 
b05ee35
 
56ddde3
b05ee35
 
 
56ddde3
b05ee35
 
 
56ddde3
b05ee35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56ddde3
 
 
 
 
b05ee35
56ddde3
b05ee35
 
 
 
56ddde3
 
b05ee35
 
 
 
56ddde3
b05ee35
 
 
 
 
56ddde3
b05ee35
 
56ddde3
b05ee35
 
 
 
 
56ddde3
 
b05ee35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56ddde3
b05ee35
 
56ddde3
b05ee35
 
56ddde3
 
 
 
b05ee35
56ddde3
 
b05ee35
 
 
 
 
 
56ddde3
 
b05ee35
56ddde3
b05ee35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56ddde3
b05ee35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56ddde3
 
 
 
b05ee35
 
 
56ddde3
 
b05ee35
 
 
56ddde3
b05ee35
 
56ddde3
 
b05ee35
 
56ddde3
 
b05ee35
56ddde3
b05ee35
56ddde3
b05ee35
 
 
 
56ddde3
b05ee35
 
 
 
 
 
 
 
56ddde3
b05ee35
56ddde3
b05ee35
56ddde3
 
 
b05ee35
 
 
 
 
56ddde3
b05ee35
 
 
56ddde3
 
 
b05ee35
56ddde3
b05ee35
56ddde3
b05ee35
 
56ddde3
b05ee35
 
 
56ddde3
b05ee35
 
 
 
 
 
 
 
 
56ddde3
b05ee35
 
 
56ddde3
b05ee35
 
 
 
56ddde3
b05ee35
56ddde3
b05ee35
56ddde3
 
 
b05ee35
56ddde3
b05ee35
56ddde3
b05ee35
 
56ddde3
b05ee35
56ddde3
b05ee35
 
 
56ddde3
b05ee35
56ddde3
b05ee35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56ddde3
b05ee35
56ddde3
 
 
 
b05ee35
 
56ddde3
 
 
b05ee35
 
56ddde3
b05ee35
 
56ddde3
b05ee35
56ddde3
 
 
b05ee35
 
56ddde3
b05ee35
 
 
 
56ddde3
 
 
 
 
 
 
 
 
 
 
 
b05ee35
 
56ddde3
b05ee35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56ddde3
b05ee35
 
 
 
56ddde3
b05ee35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56ddde3
b05ee35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56ddde3
 
b05ee35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56ddde3
 
 
b05ee35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56ddde3
 
b05ee35
 
 
56ddde3
 
 
 
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
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CosyVoice WebSocket 客户端</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
            color: #333;
        }
        .container {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }
        h1 {
            color: #2c3e50;
            margin-top: 0;
            border-bottom: 1px solid #eee;
            padding-bottom: 10px;
        }
        label {
            display: block;
            margin: 15px 0 5px;
            font-weight: bold;
        }
        input, textarea, select {
            width: 100%;
            padding: 8px;
            margin-bottom: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        button {
            background-color: #3498db;
            color: white;
            border: none;
            padding: 10px 15px;
            border-radius: 4px;
            cursor: pointer;
            margin-right: 5px;
            transition: background-color 0.3s;
        }
        button:hover {
            background-color: #2980b9;
        }
        button:disabled {
            background-color: #95a5a6;
            cursor: not-allowed;
        }
        .status {
            margin: 15px 0;
            padding: 10px;
            border-radius: 4px;
            background-color: #f9f9f9;
            border-left: 4px solid #3498db;
        }
        .error {
            border-left-color: #e74c3c;
            background-color: #fadbd8;
        }
        .success {
            border-left-color: #2ecc71;
            background-color: #d5f5e3;
        }
        .audio-controls {
            margin: 15px 0;
        }
        .voice-list {
            margin: 15px 0;
            max-height: 200px;
            overflow-y: auto;
            border: 1px solid #ddd;
            border-radius: 4px;
            padding: 10px;
        }
        .voice-item {
            padding: 8px;
            margin-bottom: 5px;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.2s;
        }
        .voice-item:hover {
            background-color: #f5f5f5;
        }
        .voice-item.selected {
            background-color: #e1f5fe;
            border-left: 3px solid #03a9f4;
        }
        .tabs {
            display: flex;
            margin-bottom: 20px;
            border-bottom: 1px solid #ddd;
        }
        .tab {
            padding: 10px 20px;
            cursor: pointer;
            border-bottom: 2px solid transparent;
        }
        .tab.active {
            border-bottom-color: #3498db;
            font-weight: bold;
        }
        .tab-content {
            display: none;
        }
        .tab-content.active {
            display: block;
        }
        .record-controls {
            display: flex;
            align-items: center;
            margin: 10px 0;
        }
        .record-button {
            background-color: #e74c3c;
            margin-right: 10px;
        }
        .record-button.recording {
            animation: pulse 1.5s infinite;
        }
        @keyframes pulse {
            0% { opacity: 1; }
            50% { opacity: 0.6; }
            100% { opacity: 1; }
        }
        .recording-status {
            margin-left: 10px;
        }
        .audio-visualizer {
            height: 60px;
            width: 100%;
            background-color: #f9f9f9;
            margin: 10px 0;
            border-radius: 4px;
            overflow: hidden;
            position: relative;
        }
        .visualizer-canvas {
            width: 100%;
            height: 100%;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>CosyVoice WebSocket 客户端</h1>
        
        <div class="tabs">
            <div class="tab active" data-tab="tts">文本转语音</div>
            <div class="tab" data-tab="upload">上传参考音频</div>
            <div class="tab" data-tab="voices">已保存音色</div>
        </div>
        
        <!-- 文本转语音选项卡 -->
        <div class="tab-content active" id="tts-tab">
            <label for="serverUrl">服务器地址:</label>
            <input type="text" id="serverUrl" value="wss://bluece-ttkkk.hf.space/ws">
            
            <label for="voiceSelect">选择音色:</label>
            <select id="voiceSelect">
                <option value="">加载中...</option>
            </select>
            <button id="refreshVoices">刷新音色列表</button>
            
            <label for="textToSpeak">要转换的文本:</label>
            <textarea id="textToSpeak" rows="5" placeholder="请输入要转换为语音的文本..."></textarea>
            
            <button id="speakButton">生成语音</button>
            <button id="stopButton" disabled>停止</button>
            
            <div class="audio-controls">
                <audio id="audioPlayer" controls></audio>
            </div>
            
            <div class="status" id="statusMessage">准备就绪,请输入文本并选择音色。</div>
        </div>
        
        <!-- 上传参考音频选项卡 -->
        <div class="tab-content" id="upload-tab">
            <div class="audio-upload">
                <label for="referenceText">参考文本:</label>
                <textarea id="referenceText" rows="3" placeholder="请输入参考音频对应的文本内容..."></textarea>
                
                <label for="voiceName">音色名称:</label>
                <input type="text" id="voiceName" placeholder="请为这个音色取一个名字...">
                
                <label>参考音频:</label>
                <div class="record-controls">
                    <button id="recordButton" class="record-button">开始录音</button>
                    <span class="recording-status" id="recordingStatus">未录音</span>
                </div>
                
                <div class="audio-visualizer">
                    <canvas id="visualizer" class="visualizer-canvas"></canvas>
                </div>
                
                <div class="audio-controls">
                    <audio id="recordedAudio" controls></audio>
                </div>
                
                <input type="file" id="audioFile" accept="audio/*">
                
                <button id="saveVoiceButton" disabled>保存音色</button>
                <div class="status" id="uploadStatus">请录制或上传参考音频。</div>
            </div>
        </div>
        
        <!-- 已保存音色选项卡 -->
        <div class="tab-content" id="voices-tab">
            <button id="listVoicesButton">获取已保存音色</button>
            
            <div class="voice-list" id="savedVoicesList">
                <p>点击"获取已保存音色"按钮查看列表。</p>
            </div>
            
            <div class="status" id="voicesStatus">准备就绪。</div>
        </div>
    </div>

    <script>
        // 全局变量
        let ws = null;
        let audioContext = null;
        let mediaRecorder = null;
        let audioChunks = [];
        let isRecording = false;
        let recordedBlob = null;
        let visualizerCanvas = document.getElementById('visualizer');
        let canvasContext = visualizerCanvas.getContext('2d');
        let audioQueue = [];
        let isPlaying = false;
        let selectedVoiceId = '';
        
        // DOM元素
        const serverUrlInput = document.getElementById('serverUrl');
        const voiceSelect = document.getElementById('voiceSelect');
        const textToSpeak = document.getElementById('textToSpeak');
        const speakButton = document.getElementById('speakButton');
        const stopButton = document.getElementById('stopButton');
        const audioPlayer = document.getElementById('audioPlayer');
        const statusMessage = document.getElementById('statusMessage');
        const tabs = document.querySelectorAll('.tab');
        const tabContents = document.querySelectorAll('.tab-content');
        const recordButton = document.getElementById('recordButton');
        const recordingStatus = document.getElementById('recordingStatus');
        const recordedAudio = document.getElementById('recordedAudio');
        const audioFile = document.getElementById('audioFile');
        const saveVoiceButton = document.getElementById('saveVoiceButton');
        const uploadStatus = document.getElementById('uploadStatus');
        const referenceText = document.getElementById('referenceText');
        const voiceName = document.getElementById('voiceName');
        const refreshVoicesButton = document.getElementById('refreshVoices');
        const listVoicesButton = document.getElementById('listVoicesButton');
        const savedVoicesList = document.getElementById('savedVoicesList');
        const voicesStatus = document.getElementById('voicesStatus');
        
        // 初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 设置标签页切换
            tabs.forEach(tab => {
                tab.addEventListener('click', () => {
                    tabs.forEach(t => t.classList.remove('active'));
                    tabContents.forEach(c => c.classList.remove('active'));
                    tab.classList.add('active');
                    document.getElementById(`${tab.dataset.tab}-tab`).classList.add('active');
                });
            });
            
            // 初始化音频上下文
            try {
                window.AudioContext = window.AudioContext || window.webkitAudioContext;
                audioContext = new AudioContext();
            } catch (e) {
                showStatus('您的浏览器不支持Web Audio API', true);
            }
            
            // 调整可视化器画布大小
            resizeCanvas();
            window.addEventListener('resize', resizeCanvas);
            
            // 连接WebSocket
            connectWebSocket();
            
            // 设置事件监听器
            setupEventListeners();
        });
        
        function resizeCanvas() {
            visualizerCanvas.width = visualizerCanvas.clientWidth;
            visualizerCanvas.height = visualizerCanvas.clientHeight;
        }
        
        function setupEventListeners() {
            // 连接按钮
            serverUrlInput.addEventListener('change', connectWebSocket);
            
            // 语音生成按钮
            speakButton.addEventListener('click', generateSpeech);
            stopButton.addEventListener('click', stopSpeech);
            
            // 录音按钮
            recordButton.addEventListener('click', toggleRecording);
            
            // 文件上传
            audioFile.addEventListener('change', handleFileUpload);
            
            // 保存音色按钮
            saveVoiceButton.addEventListener('click', saveVoice);
            
            // 刷新音色列表按钮
            refreshVoicesButton.addEventListener('click', fetchVoices);
            
            // 获取已保存音色按钮
            listVoicesButton.addEventListener('click', fetchVoices);
        }
        
        function connectWebSocket() {
            // 关闭现有连接
            if (ws) {
                ws.close();
            }
            
            const serverUrl = serverUrlInput.value.trim();
            if (!serverUrl) {
                showStatus('请输入服务器地址', true);
                return;
            }
            
            try {
                ws = new WebSocket(serverUrl);
                
                ws.onopen = function() {
                    showStatus('已连接到服务器');
                    fetchVoices();
                };
                
                ws.onclose = function() {
                    showStatus('与服务器的连接已关闭', true);
                };
                
                ws.onerror = function(error) {
                    showStatus('WebSocket错误: ' + error.message, true);
                };
                
                ws.onmessage = function(event) {
                    handleServerMessage(event.data);
                };
            } catch (error) {
                showStatus('连接错误: ' + error.message, true);
            }
        }
        
        function fetchVoices() {
            if (!ws || ws.readyState !== WebSocket.OPEN) {
                showStatus('未连接到服务器', true);
                return;
            }
            
            // 发送获取语音列表请求
            ws.send(JSON.stringify({
                action: 'list_voices'
            }));
            
            showStatus('正在获取可用音色...');
        }
        
        function generateSpeech() {
            if (!ws || ws.readyState !== WebSocket.OPEN) {
                showStatus('未连接到服务器', true);
                return;
            }
            
            const text = textToSpeak.value.trim();
            if (!text) {
                showStatus('请输入要转换的文本', true);
                return;
            }
            
            const voiceId = voiceSelect.value;
            if (!voiceId) {
                showStatus('请选择音色', true);
                return;
            }
            
            // 清空音频队列
            audioQueue = [];
            isPlaying = false;
            
            // 发送TTS请求
            ws.send(JSON.stringify({
                action: 'tts',
                text: text,
                voice_id: voiceId
            }));
            
            speakButton.disabled = true;
            stopButton.disabled = false;
            showStatus('正在生成语音...');
        }
        
        function stopSpeech() {
            // 清空音频队列
            audioQueue = [];
            isPlaying = false;
            
            // 停止当前播放
            audioPlayer.pause();
            audioPlayer.currentTime = 0;
            
            speakButton.disabled = false;
            stopButton.disabled = true;
            showStatus('已停止语音生成');
        }
        
        function handleServerMessage(data) {
            try {
                const message = JSON.parse(data);
                
                switch (message.type) {
                    case 'start':
                        showStatus('开始生成语音...');
                        break;
                        
                    case 'audio':
                        // 接收音频数据
                        handleAudioData(message.data, message.sample_rate);
                        break;
                        
                    case 'end':
                        speakButton.disabled = false;
                        stopButton.disabled = true;
                        showStatus('语音生成完成');
                        break;
                        
                    case 'error':
                        speakButton.disabled = false;
                        stopButton.disabled = true;
                        showStatus('错误: ' + message.message, true);
                        break;
                        
                    case 'info':
                        showStatus(message.message);
                        break;
                        
                    case 'voices':
                        updateVoicesList(message.data);
                        break;
                        
                    case 'voice_saved':
                        saveVoiceButton.disabled = true;
                        showUploadStatus('音色保存成功! ID: ' + message.voice_id, false);
                        fetchVoices();  // 刷新音色列表
                        break;
                        
                    default:
                        console.log('未知消息类型:', message);
                }
            } catch (error) {
                console.error('处理服务器消息时出错:', error);
                showStatus('处理服务器消息时出错', true);
            }
        }
        
        function handleAudioData(base64Data, sampleRate) {
            // 解码base64数据
            const binaryString = atob(base64Data);
            const len = binaryString.length;
            const bytes = new Uint8Array(len);
            
            for (let i = 0; i < len; i++) {
                bytes[i] = binaryString.charCodeAt(i);
            }
            
            // 创建音频Blob
            const audioBlob = new Blob([bytes], { type: 'audio/wav' });
            
            // 添加到音频队列
            audioQueue.push(audioBlob);
            
            // 如果没有在播放,开始播放
            if (!isPlaying) {
                playNextAudio();
            }
        }
        
        function playNextAudio() {
            if (audioQueue.length === 0) {
                isPlaying = false;
                return;
            }
            
            isPlaying = true;
            const audioBlob = audioQueue.shift();
            const audioUrl = URL.createObjectURL(audioBlob);
            
            audioPlayer.src = audioUrl;
            audioPlayer.play()
                .then(() => {
                    // 音频播放结束后释放URL
                    audioPlayer.onended = function() {
                        URL.revokeObjectURL(audioUrl);
                        playNextAudio();
                    };
                })
                .catch(error => {
                    console.error('播放音频时出错:', error);
                    URL.revokeObjectURL(audioUrl);
                    playNextAudio();
                });
        }
        
        function updateVoicesList(voices) {
            // 更新下拉选择框
            voiceSelect.innerHTML = '';
            
            if (voices.length === 0) {
                const option = document.createElement('option');
                option.value = '';
                option.textContent = '没有可用的音色';
                voiceSelect.appendChild(option);
                showStatus('没有可用的音色');
            } else {
                voices.forEach(voice => {
                    const option = document.createElement('option');
                    option.value = voice.ShortName;
                    option.textContent = `${voice.FriendlyName} (${voice.Gender}, ${voice.Locale})`;
                    voiceSelect.appendChild(option);
                });
                
                showStatus(`已加载 ${voices.length} 个音色`);
                
                // 如果之前有选择的音色,尝试恢复选择
                if (selectedVoiceId) {
                    voiceSelect.value = selectedVoiceId;
                }
                
                // 更新已保存音色列表
                updateSavedVoicesList(voices);
            }
        }
        
        function updateSavedVoicesList(voices) {
            savedVoicesList.innerHTML = '';
            
            if (voices.length === 0) {
                savedVoicesList.innerHTML = '<p>没有保存的音色</p>';
                voicesStatus.textContent = '没有保存的音色';
                return;
            }
            
            voices.forEach(voice => {
                const voiceItem = document.createElement('div');
                voiceItem.className = 'voice-item';
                voiceItem.dataset.voiceId = voice.ShortName;
                
                voiceItem.innerHTML = `
                    <strong>${voice.FriendlyName}</strong>
                    <div>ID: ${voice.ShortName}</div>
                    <div>性别: ${voice.Gender}, 语言: ${voice.Locale}</div>
                `;
                
                voiceItem.addEventListener('click', function() {
                    // 移除其他选中项的高亮
                    document.querySelectorAll('.voice-item').forEach(item => {
                        item.classList.remove('selected');
                    });
                    
                    // 高亮当前选中项
                    this.classList.add('selected');
                    
                    // 设置选中的音色ID
                    selectedVoiceId = this.dataset.voiceId;
                    
                    // 切换到TTS选项卡并设置选择框
                    tabs[0].click();
                    voiceSelect.value = selectedVoiceId;
                });
                
                savedVoicesList.appendChild(voiceItem);
            });
            
            voicesStatus.textContent = `共有 ${voices.length} 个保存的音色`;
        }
        
        async function toggleRecording() {
            if (isRecording) {
                // 停止录音
                stopRecording();
            } else {
                // 开始录音
                startRecording();
            }
        }
        
        async function startRecording() {
            try {
                // 请求麦克风权限
                const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
                
                // 设置可视化
                setupAudioVisualization(stream);
                
                // 创建MediaRecorder
                mediaRecorder = new MediaRecorder(stream);
                audioChunks = [];
                
                mediaRecorder.ondataavailable = function(event) {
                    audioChunks.push(event.data);
                };
                
                mediaRecorder.onstop = function() {
                    // 创建音频Blob
                    recordedBlob = new Blob(audioChunks, { type: 'audio/wav' });
                    const audioUrl = URL.createObjectURL(recordedBlob);
                    
                    // 设置音频播放器
                    recordedAudio.src = audioUrl;
                    recordedAudio.style.display = 'block';
                    
                    // 启用保存按钮
                    saveVoiceButton.disabled = false;
                };
                
                // 开始录音
                mediaRecorder.start();
                isRecording = true;
                
                // 更新UI
                recordButton.textContent = '停止录音';
                recordButton.classList.add('recording');
                recordingStatus.textContent = '正在录音...';
                
            } catch (error) {
                console.error('录音时出错:', error);
                showUploadStatus('无法访问麦克风: ' + error.message, true);
            }
        }
        
        function stopRecording() {
            if (mediaRecorder && isRecording) {
                mediaRecorder.stop();
                isRecording = false;
                
                // 更新UI
                recordButton.textContent = '开始录音';
                recordButton.classList.remove('recording');
                recordingStatus.textContent = '录音完成';
            }
        }
        
        function setupAudioVisualization(stream) {
            const audioSource = audioContext.createMediaStreamSource(stream);
            const analyser = audioContext.createAnalyser();
            analyser.fftSize = 256;
            
            audioSource.connect(analyser);
            
            const bufferLength = analyser.frequencyBinCount;
            const dataArray = new Uint8Array(bufferLength);
            
            canvasContext.clearRect(0, 0, visualizerCanvas.width, visualizerCanvas.height);
            
            function draw() {
                if (!isRecording) return;
                
                requestAnimationFrame(draw);
                
                analyser.getByteFrequencyData(dataArray);
                
                canvasContext.fillStyle = '#f5f5f5';
                canvasContext.fillRect(0, 0, visualizerCanvas.width, visualizerCanvas.height);
                
                const barWidth = (visualizerCanvas.width / bufferLength) * 2.5;
                let x = 0;
                
                for (let i = 0; i < bufferLength; i++) {
                    const barHeight = (dataArray[i] / 255) * visualizerCanvas.height;
                    
                    canvasContext.fillStyle = `rgb(50, ${dataArray[i] + 100}, 200)`;
                    canvasContext.fillRect(x, visualizerCanvas.height - barHeight, barWidth, barHeight);
                    
                    x += barWidth + 1;
                }
            }
            
            draw();
        }
        
        function handleFileUpload(event) {
            const file = event.target.files[0];
            if (!file) return;
            
            // 检查文件类型
            if (!file.type.startsWith('audio/')) {
                showUploadStatus('请选择音频文件', true);
                return;
            }
            
            // 读取文件
            const reader = new FileReader();
            reader.onload = function(e) {
                // 创建音频Blob
                recordedBlob = new Blob([e.target.result], { type: file.type });
                const audioUrl = URL.createObjectURL(recordedBlob);
                
                // 设置音频播放器
                recordedAudio.src = audioUrl;
                recordedAudio.style.display = 'block';
                
                // 启用保存按钮
                saveVoiceButton.disabled = false;
                
                showUploadStatus('音频文件已加载');
            };
            
            reader.onerror = function() {
                showUploadStatus('读取文件时出错', true);
            };
            
            reader.readAsArrayBuffer(file);
        }
        
        function saveVoice() {
            if (!ws || ws.readyState !== WebSocket.OPEN) {
                showUploadStatus('未连接到服务器', true);
                return;
            }
            
            const refText = referenceText.value.trim();
            if (!refText) {
                showUploadStatus('请输入参考文本', true);
                return;
            }
            
            const name = voiceName.value.trim();
            if (!name) {
                showUploadStatus('请输入音色名称', true);
                return;
            }
            
            if (!recordedBlob) {
                showUploadStatus('请先录制或上传音频', true);
                return;
            }
            
            // 读取音频数据
            const reader = new FileReader();
            reader.onload = function(e) {
                const audioData = e.target.result;
                const base64Data = audioData.split(',')[1];
                
                // 发送保存音色请求
                ws.send(JSON.stringify({
                    action: 'save_voice',
                    audio_data: base64Data,
                    reference_text: refText,
                    voice_name: name
                }));
                
                showUploadStatus('正在保存音色...');
                saveVoiceButton.disabled = true;
            };
            
            reader.onerror = function() {
                showUploadStatus('读取音频数据时出错', true);
            };
            
            reader.readAsDataURL(recordedBlob);
        }
        
        function showStatus(message, isError = false) {
            statusMessage.textContent = message;
            statusMessage.className = isError ? 'status error' : 'status';
        }
        
        function showUploadStatus(message, isError = false) {
            uploadStatus.textContent = message;
            uploadStatus.className = isError ? 'status error' : 'status';
        }
    </script>
</body>
</html>