index.html 13.6 KB
Newer Older
chenzk's avatar
v1.0  
chenzk committed
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
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>VITA-Audio Demo</title>
    <script src="https://unpkg.com/socket.io-client@4.8.1/dist/socket.io.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">
    <style>
        body {
            min-height: 100vh;
            margin: 0;
            font-family: 'Segoe UI', Arial, sans-serif;
            background: linear-gradient(135deg, #e0e7ff 0%, #f0f0f0 100%);
        }

        /* 让登录区和主内容区都居中 */
        #authSection, #mainSection {
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            width: 100vw;
        }

        .container, #authSection {
            max-height: 90vh;
            overflow: auto;
        }

        .container {
            text-align: center;
            background: rgba(255,255,255,0.95);
            padding: 30px 30px 20px 30px;
            border-radius: 18px;
            box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.15);
            max-width: 700px;
            width: 100%;
            margin: 0 auto; /* 水平居中 */
        }

        .banner-img {
            width: 100%;
            max-width: 600px;
            border-radius: 12px;
            margin-bottom: 18px;
            box-shadow: 0 2px 12px rgba(0,0,0,0.08);
        }

        h1 {
            margin-top: 0;
            font-size: 2.2rem;
            color: #3b3b6d;
            letter-spacing: 1px;
        }
        h2 {
            color: #5a5a89;
            font-size: 1.2rem;
            margin-bottom: 8px;
            margin-top: 24px;
            display: flex;
            align-items: center;
            gap: 8px;
            justify-content: center;
        }
        canvas {
            border: 1.5px solid #b3b3e6;
            margin: 10px 0;
            border-radius: 8px;
            background: #f8f9ff;
        }
        button {
            margin: 5px;
            padding: 10px 28px;
            font-size: 16px;
            border: none;
            border-radius: 24px;
            background: linear-gradient(90deg, #6a82fb 0%, #fc5c7d 100%);
            color: white;
            font-weight: 600;
            cursor: pointer;
            transition: box-shadow 0.2s, transform 0.2s;
            box-shadow: 0 2px 8px rgba(100,100,200,0.08);
        }
        button:disabled {
            background: #bdbdbd;
            cursor: not-allowed;
        }
        button:hover:not(:disabled) {
            box-shadow: 0 4px 16px rgba(100,100,200,0.18);
            transform: translateY(-2px) scale(1.03);
        }
        .alert {
            display: none;
            margin-top: 20px;
            padding: 10px;
            background-color: #f44336;
            color: white;
            border-radius: 5px;
        }
        .text-input-container {
            margin-top: 30px;
        }
        .text-input-container textarea {
            padding: 12px;
            font-size: 16px;
            width: 90%;
            height: 120px;
            margin-bottom: 18px;
            border-radius: 10px;
            border: 1.5px solid #b3b3e6;
            background: #f8f9ff;
            resize: none;
            overflow: auto;
            word-wrap: break-word;
            transition: border 0.2s;
        }
        .text-input-container textarea:focus {
            border: 1.5px solid #6a82fb;
            outline: none;
        }
        .input-icon {
            margin-right: 6px;
            color: #6a82fb;
        }
        .audio-icon {
            color: #fc5c7d;
            margin-right: 6px;
        }
        .time-box {
            font-size: 1.2rem;
            padding: 12px;
            background-color: #e0e7ff;
            border-radius: 8px;
            color: #3b3b6d;
            text-align: center;
            margin-top: 10px;
            font-weight: 600;
        }
        /* Responsive */
        @media (max-width: 800px) {
            .container { max-width: 98vw; }
            .banner-img { max-width: 98vw; }
        }
    </style>
</head>
<body>
    <!-- 鉴权区 -->
    <!-- <div id="authSection" style="display: block;">
        <h2><i class="fa-solid fa-lock"></i>Login</h2>
        <input type="password" id="password" placeholder="Enter password" style="padding:10px; border-radius:8px; border:1.5px solid #b3b3e6; font-size:16px;">
        <button id="loginButton">Login</button>
    </div> -->
    <!-- 主内容区 -->
    <!-- <div id="mainSection" style="display: none;"> -->
    <div id="mainSection">
        <div class="container">
            <img src="https://raw.githubusercontent.com/VITA-MLLM/VITA-Audio/refs/heads/main/asset/vita-audio_logo.jpg" class="banner-img" alt="Banner">
            <!-- <h1>VITA-Audio Demo</h1> -->
            <button id="startButton"><i class="fa-solid fa-microphone"></i> Dialogue Start</button>
            <button id="stopButton" disabled><i class="fa-solid fa-stop"></i> Dialogue Stop</button>
            <h2><i class="fa-solid fa-wave-square audio-icon"></i>Input Waveform</h2>
            <canvas id="inputCanvas" width="600" height="100"></canvas>
            <h2><i class="fa-solid fa-wave-square audio-icon"></i>Output Waveform</h2>
            <canvas id="outputCanvas" width="600" height="100"></canvas>
            <audio id="remoteAudio" autoplay playsinline></audio>
            <div id="alertBox" class="alert">Too many users connected. Please refresh and try again.</div>
            <div id="alertBox2" class="alert">Connect time out. Please refresh and reconnect.</div>
            <div id="alertBox3" class="alert">Prompt set success.</div>
            <h2><i class="fa-solid fa-clock"></i> First Audio Generation Time</h2>
            <div id="generationTime" class="time-box">
                Waiting for first audio...
            </div>
    </div>
    
    <script>
        // 鉴权相关
        // const passwordInput = document.getElementById('password');
        // const loginButton = document.getElementById('loginButton');
        // const authSection = document.getElementById('authSection');
        // const mainSection = document.getElementById('mainSection');
        // const socket = io({ transports: ['websocket'] });

        // // Handle login
        // loginButton.addEventListener('click', function() {
        //     const password = passwordInput.value;
        //     socket.emit('authenticate', { password: password });
        // });

        // // Listen for authentication success
        // socket.on('authenticated', function() {
        //     authSection.style.display = 'none';
        //     mainSection.style.display = 'block';
        // });

        // // Listen for authentication failure
        // socket.on('authentication_failed', function() {
        //     alert('Authentication failed. Please try again.');
        // });

        const mainSection = document.getElementById('mainSection');
        const socket = io({ transports: ['websocket'] });
        socket.on('first_audio_time', function(data) {
            // data.time 是后端发来的时间字符串
            document.getElementById('generationTime').textContent = data.time;
        });
        // 主功能相关
        const remoteAudio = document.getElementById('remoteAudio');
        const startButton = document.getElementById('startButton');
        const stopButton = document.getElementById('stopButton');
        const inputCanvas = document.getElementById('inputCanvas');
        const outputCanvas = document.getElementById('outputCanvas');
        const inputCtx = inputCanvas.getContext('2d');
        const outputCtx = outputCanvas.getContext('2d');
        const alertBox = document.getElementById('alertBox');
        const alertBox2 = document.getElementById('alertBox2');
        const alertBox3 = document.getElementById('alertBox3');
        // <div id="audioGenerationTimeBox" class="alert" style="display: none;">
        //     First Audio Generation Time: <span id="audioGenerationTime">0</span> ms
        // </div>

        const audioQueue = [];
        let isPlaying = false;
        let currentSource = null;

        let localStream;
        let audioContext;
        let audioContext2;
        let processor;
        let isRecording = false;
        const fixedSampleRate = 16000;

        startButton.addEventListener('click', startRecording);
        stopButton.addEventListener('click', stopRecording);
        audioContext2 = new (window.AudioContext || window.webkitAudioContext)({ sampleRate: 22050 });

        async function startRecording() {
            audioQueue.length = 0;
            if (currentSource) {
                currentSource.stop();
                currentSource = null;
            }
            isPlaying = false;
            
            if (audioContext) {
                audioContext.close();
            }
            if (processor) {
                processor.disconnect();
            }

            localStream = await navigator.mediaDevices.getUserMedia({ audio: {autoGainControl: false, echoCancellation: true, noiseSuppression: false, latency: 0.001} });

            audioContext = new (window.AudioContext || window.webkitAudioContext)({ sampleRate: fixedSampleRate });
            const input = audioContext.createMediaStreamSource(localStream);
            processor = audioContext.createScriptProcessor(256, 1, 1);

            processor.onaudioprocess = (e) => {
                if (!isRecording) return;

                const inputData = e.inputBuffer.getChannelData(0);

                const int16Array = new Int16Array(inputData.length);
                for (let i = 0; i < inputData.length; i++) {
                    int16Array[i] = inputData[i] * 0x7FFF;
                }
                socket.emit('audio', JSON.stringify({ sample_rate: audioContext.sampleRate, audio: Array.from(new Uint8Array(int16Array.buffer)) }));
                drawWaveform(inputData, inputCtx);
            };

            input.connect(processor);
            processor.connect(audioContext.destination);

            isRecording = true;
            startButton.disabled = true;
            stopButton.disabled = false;

            socket.emit('recording-started');
        }

        function stopRecording() {
            audioQueue.length = 0;
            if (currentSource) {
                currentSource.stop();
                currentSource = null;
            }
            isPlaying = false;
            isRecording = false;
            if (localStream) {
                localStream.getTracks().forEach(track => track.stop());
            }
            startButton.disabled = false;
            stopButton.disabled = true;

            socket.emit('recording-stopped');
        }

        socket.on('too_many_users', (data) => {
            alert('Too many users connected. Please refresh and try again.');
        });

        socket.on('out_time', (data) => {
            alert('Connect time out. Please refresh and reconnect.');
        });

        socket.on('prompt_success', (data) => {
            alert('Prompt set success. Please restart interaction.');
        });
        
        socket.on('audio', (data) => {
            // console.log('audio event:', data, data instanceof ArrayBuffer, data?.type, data?.data?.length);
            audioQueue.push(data);
            if (!isPlaying) {
                playNextAudio();
            }
        });
        socket.on('stop_tts', () => {
            audioQueue.length = 0;
            if (currentSource) {
                currentSource.stop();
                currentSource = null;
            }
            isPlaying = false;
        });

        function playNextAudio() {
            if (audioQueue.length === 0) {
                isPlaying = false;
                socket.emit('tts_stopped');
                return;
            }

            isPlaying = true;
            socket.emit('tts_playing');

            const data = audioQueue.shift();

            let int16Array;
            if (data instanceof ArrayBuffer) {
                int16Array = new Int16Array(data);
            } else if (data && data.type === 'Buffer' && Array.isArray(data.data)) {
                const uint8 = new Uint8Array(data.data);
                int16Array = new Int16Array(uint8.buffer);
            } else {
                console.error('Unknown audio data format', data);
                return;
            }

            const float32Array = new Float32Array(int16Array.length);
            for (let i = 0; i < int16Array.length; i++) {
                float32Array[i] = int16Array[i] / 32768.0;
            }

            const audioBuffer = audioContext2.createBuffer(1, float32Array.length, audioContext2.sampleRate);
            drawWaveform(float32Array, outputCtx);
            audioBuffer.copyToChannel(float32Array, 0);
            const source = audioContext2.createBufferSource();
            source.buffer = audioBuffer;
            source.connect(audioContext2.destination);
            source.start();

            currentSource = source;

            source.onended = () => {
                currentSource = null;
                playNextAudio();
            };
        }

        function drawWaveform(data, context) {
            context.clearRect(0, 0, context.canvas.width, context.canvas.height);
            context.beginPath();
            context.moveTo(0, context.canvas.height / 2);
            for (let i = 0; i < data.length; i++) {
                const x = (i / data.length) * context.canvas.width;
                const y = (1 - data[i]) * context.canvas.height / 2;
                context.lineTo(x, y);
            }
            context.stroke();
        }

    </script>
</body>
</html>