index1.html 15 KB
Newer Older
何处是我家's avatar
提交  
何处是我家 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
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
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>语音交互系统</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .section {
            margin-bottom: 20px;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 8px;
            background-color: white;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        h2 {
            color: #333;
            border-bottom: 1px solid #eee;
            padding-bottom: 10px;
        }
        button {
            padding: 10px 15px;
            margin-right: 10px;
            margin-bottom: 10px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: background-color 0.3s;
        }
        button:hover {
            background-color: #45a049;
        }
        button:disabled {
            background-color: #cccccc;
            cursor: not-allowed;
        }
        #transcript, #response {
            margin-top: 10px;
            padding: 12px;
            border: 1px solid #ccc;
            min-height: 100px;
            border-radius: 4px;
            background-color: #f9f9f9;
            font-size: 14px;
            line-height: 1.5;
        }
        input[type="text"] {
            width: 100%;
            padding: 10px;
            margin-bottom: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }
        .audio-controls {
            margin-top: 10px;
            display: flex;
            gap: 10px;
        }
        .audio-player {
            margin-top: 15px;
        }
        .loading {
            display: none;
            margin: 15px 0;
            padding: 10px;
            background-color: #f0f0f0;
            border-radius: 4px;
            text-align: center;
            color: #666;
        }
        .save-controls {
            margin-top: 15px;
            display: flex;
            gap: 10px;
        }
        .interaction-history {
            margin-top: 20px;
            padding: 10px;
            background-color: #f0f0f0;
            border-radius: 4px;
            max-height: 200px;
            overflow-y: auto;
        }
        .user-message {
            background-color: #e3f2fd;
            padding: 10px;
            border-radius: 4px;
            margin-bottom: 10px;
        }
        .system-message {
            background-color: #e8f5e9;
            padding: 10px;
            border-radius: 4px;
            margin-bottom: 10px;
        }
    </style>
</head>
<body>
<div class="section">
    <h2>语音交互系统</h2>
    <p>支持语音输入和文字输入,系统将自动回答您的问题。</p>
</div>

<div class="section">
    <h2>语音输入</h2>
    <div class="audio-controls">
        <button id="startRecording">开始录音</button>
        <button id="stopRecording" disabled>停止录音</button>
    </div>
    <div id="transcript" contenteditable="true">录音转写内容将显示在这里...</div>
</div>

<div class="section">
    <h2>文字输入</h2>
    <input type="text" id="textInput" placeholder="请输入文字">
    <button id="textSubmit">提交文字</button>
    <div id="response">系统回答将显示在这里...</div>
</div>

<div class="section">
    <h2>音频播放</h2>
    <div class="audio-player">
        <h3>用户录音:</h3>
        <audio id="userAudio" controls></audio>
        <h3>系统回答:</h3>
        <audio id="systemAudio" controls></audio>
    </div>
    <div class="loading" id="loading">正在处理请求,请稍候...</div>
    <div class="save-controls">
        <button id="saveWav">保存为WAV</button>
        <button id="savePcm">保存为PCM</button>
    </div>
</div>

<div class="section">
    <h2>交互历史</h2>
    <div id="interactionHistory" class="interaction-history"></div>
</div>

<script>
    let audioContext;
    let mediaStream;
    let scriptProcessor;
    let audioBuffer = [];
    let isRecording = false;
    const TARGET_SAMPLE_RATE = 16000;
    let lastRecordedPcmData = null;
    let lastRecordedWavBlob = null;

    // 初始化音频上下文
    function initAudioContext() {
        audioContext = new (window.AudioContext || window.webkitAudioContext)({
            sampleRate: TARGET_SAMPLE_RATE
        });
    }

    // 开始录音
    document.getElementById('startRecording').addEventListener('click', async () => {
        try {
            const stream = await navigator.mediaDevices.getUserMedia({
                audio: {
                    sampleRate: TARGET_SAMPLE_RATE,
                    channelCount: 1,
                    echoCancellation: true,
                    noiseSuppression: true
                }
            });
            mediaStream = stream;
            initAudioContext();

            const source = audioContext.createMediaStreamSource(stream);
            scriptProcessor = audioContext.createScriptProcessor(16384, 1, 1);
            scriptProcessor.onaudioprocess = handleAudioProcess;
            source.connect(scriptProcessor);
            scriptProcessor.connect(audioContext.destination);

            isRecording = true;
            document.getElementById('startRecording').disabled = true;
            document.getElementById('stopRecording').disabled = false;
        } catch (err) {
            console.error('录音错误:', err);
            alert('无法启动录音,请检查麦克风权限。');
        }
    });

    // 处理音频数据
    function handleAudioProcess(event) {
        if (!isRecording) return;
        const inputBuffer = event.inputBuffer;
        const data = inputBuffer.getChannelData(0);
        audioBuffer.push(new Float32Array(data));
    }

    // 停止录音
    document.getElementById('stopRecording').addEventListener('click', () => {
        if (mediaStream && isRecording) {
            mediaStream.getTracks().forEach(track => track.stop());
            scriptProcessor.disconnect();
            isRecording = false;
            document.getElementById('startRecording').disabled = false;
            document.getElementById('stopRecording').disabled = true;

            // 将音频数据转换为PCM
            convertAudioBufferToPCM();
        }
    });

    // 将音频数据转换为PCM
    function convertAudioBufferToPCM() {
        // 计算总采样点数
        let totalSamples = 0;
        for (let i = 0; i < audioBuffer.length; i++) {
            totalSamples += audioBuffer[i].length;
        }

        // 创建正确大小的数组
        const audioData = new Float32Array(totalSamples);
        let offset = 0;

        // 复制音频数据
        for (let i = 0; i < audioBuffer.length; i++) {
            audioData.set(audioBuffer[i], offset);
            offset += audioBuffer[i].length;
        }

        // 将Float32Array转换为Int16Array(PCM格式)
        const pcmData = new Int16Array(audioData.length);
        for (let i = 0; i < audioData.length; i++) {
            pcmData[i] = Math.max(-1, Math.min(1, audioData[i])) * 0x7FFF;
        }

        // 创建WAV文件头
        const wavHeader = new Uint8Array([
            82, 73, 70, 70, // "RIFF" 标识
            0, 0, 0, 0,     // 文件大小(待填充)
            87, 65, 86, 69, // "WAVE" 标识
            102, 109, 116, 32, // "fmt " 标识
            16, 0, 0, 0,    // fmt块大小
            1, 0,           // 音频格式,1表示PCM
            1, 0,           // 声道数,1表示单声道
            TARGET_SAMPLE_RATE & 0xFF, (TARGET_SAMPLE_RATE >> 8) & 0xFF, (TARGET_SAMPLE_RATE >> 16) & 0xFF, (TARGET_SAMPLE_RATE >> 24) & 0xFF, // 采样率
            (TARGET_SAMPLE_RATE * 2) & 0xFF, ((TARGET_SAMPLE_RATE * 2) >> 8) & 0xFF, ((TARGET_SAMPLE_RATE * 2) >> 16) & 0xFF, ((TARGET_SAMPLE_RATE * 2) >> 24) & 0xFF, // 字节率
            2, 0,           // 块对齐
            16, 0,          // 位深度
            100, 97, 116, 97, // "data" 标识
            0, 0, 0, 0      // 数据大小(待填充)
        ]);

        // 填充文件大小和数据大小
        const dataSize = pcmData.length * 2; // 16位 = 2字节
        const fileSize = dataSize + 36; // 文件总大小 = 数据大小 + 头部大小(44字节)

        // 填充文件大小(4-7字节)
        wavHeader[4] = fileSize & 0xFF;
        wavHeader[5] = (fileSize >> 8) & 0xFF;
        wavHeader[6] = (fileSize >> 16) & 0xFF;
        wavHeader[7] = (fileSize >> 24) & 0xFF;

        // 填充数据大小(40-43字节)
        wavHeader[40] = dataSize & 0xFF;
        wavHeader[41] = (dataSize >> 8) & 0xFF;
        wavHeader[42] = (dataSize >> 16) & 0xFF;
        wavHeader[43] = (dataSize >> 24) & 0xFF;

        // 创建WAV Blob
        lastRecordedWavBlob = new Blob([wavHeader, pcmData.buffer], { type: 'audio/wav' });
        lastRecordedPcmData = pcmData;

        // 创建音频URL并播放
        const audioUrl = URL.createObjectURL(lastRecordedWavBlob);
        document.getElementById('userAudio').src = audioUrl;
        document.getElementById('userAudio').load();

        // 上传PCM数据
        const formData = new FormData();
        const pcmBlob = new Blob([pcmData.buffer], { type: 'audio/pcm' });
        formData.append('audio', pcmBlob, 'recording.pcm');

        // 显示加载提示
        document.getElementById('loading').style.display = 'block';

        // 发送到后端进行处理
        fetchAudioResponse(formData);
    }

    // 保存WAV文件
    document.getElementById('saveWav').addEventListener('click', () => {
        if (lastRecordedWavBlob) {
            const url = URL.createObjectURL(lastRecordedWavBlob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `recording_${new Date().toISOString().replace(/[:.]/g, '-')}.wav`;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
        } else {
            alert('没有可保存的录音!');
        }
    });

    // 保存PCM文件
    document.getElementById('savePcm').addEventListener('click', () => {
        if (lastRecordedPcmData) {
            const pcmBlob = new Blob([lastRecordedPcmData.buffer], { type: 'audio/pcm' });
            const url = URL.createObjectURL(pcmBlob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `recording_${new Date().toISOString().replace(/[:.]/g, '-')}.pcm`;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
        } else {
            alert('没有可保存的录音!');
        }
    });

    // 文字输入功能
    document.getElementById('textSubmit').addEventListener('click', () => {
        const text = document.getElementById('textInput').value.trim();
        if (!text) {
            alert('请输入文字内容!');
            return;
        }

        // 创建表单数据
        const formData = new FormData();
        formData.append('context', text);

        // 显示加载提示
        document.getElementById('loading').style.display = 'block';

        // 发送到后端进行处理
        fetchAudioResponse(formData);
    });

    // 获取音频响应
    function fetchAudioResponse(formData) {
        const systemAudio = document.getElementById('systemAudio');
        const loading = document.getElementById('loading');

        // 创建MediaSource
        const mediaSource = new MediaSource();
        systemAudio.src = URL.createObjectURL(mediaSource);

        // 准备接收数据
        mediaSource.addEventListener('sourceopen', () => {
            // 检查浏览器是否支持所需的MIME类型
            if (!MediaSource.isTypeSupported('audio/mpeg')) {
                console.error('浏览器不支持audio/mpeg格式');
                loading.style.display = 'none';
                return;
            }

            const sourceBuffer = mediaSource.addSourceBuffer('audio/mpeg');
            const queue = [];
            let isAppending = false;

            function appendNextChunk() {
                if (queue.length > 0 && !isAppending && !sourceBuffer.updating) {
                    isAppending = true;
                    const chunk = queue.shift();
                    sourceBuffer.appendBuffer(chunk);
                }
            }

            sourceBuffer.addEventListener('updateend', () => {
                isAppending = false;
                appendNextChunk();
            });

            sourceBuffer.addEventListener('error', (e) => {
                console.error('SourceBuffer error:', e);
                loading.style.display = 'none';
            });

            // 发送请求到后端
            fetch('http://localhost:26061/dify/audio/voice', {
                method: 'POST',
                body: formData
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.body;
                })
                .then(stream => {
                    const reader = stream.getReader();
                    return readStream(reader, queue, appendNextChunk, sourceBuffer, loading);
                })
                .catch(error => {
                    console.error('Error fetching audio response:', error);
                    loading.style.display = 'none';
                });
        });
    }

    function readStream(reader, queue, appendNextChunk, sourceBuffer, loading) {
        function processResult() {
            reader.read().then(({ done, value }) => {
                if (done) {
                    sourceBuffer.abort();
                    loading.style.display = 'none';
                    return;
                }
                if (value && value.byteLength > 0) {
                    queue.push(value);
                    appendNextChunk();
                }
                processResult();
            }).catch(error => {
                console.error('Error reading stream:', error);
                loading.style.display = 'none';
            });
        }
        processResult();
    }

    // 添加消息到历史记录
    function addToHistory(type, content) {
        const historyDiv = document.getElementById('interactionHistory');
        const messageDiv = document.createElement('div');

        if (type === 'user') {
            messageDiv.className = 'user-message';
            messageDiv.textContent = `用户: ${content}`;
        } else if (type === 'system') {
            messageDiv.className = 'system-message';
            messageDiv.textContent = `系统: ${content}`;
        }

        historyDiv.appendChild(messageDiv);
        historyDiv.scrollTop = historyDiv.scrollHeight;
    }
</script>
</body>
</html>