|
| 1 | +<!DOCTYPE html> |
| 2 | +<html> |
| 3 | +<head> |
| 4 | + <title>Mic to WebSocket</title> |
| 5 | +</head> |
| 6 | +<body> |
| 7 | + <button id="startBtn">Start Mic</button> |
| 8 | + <div id="status"></div> |
| 9 | + |
| 10 | + <script> |
| 11 | + const startBtn = document.getElementById('startBtn'); |
| 12 | + const statusDiv = document.getElementById('status'); |
| 13 | + let isRecording = false; |
| 14 | + let socket; |
| 15 | + |
| 16 | + startBtn.addEventListener('click', async () => { |
| 17 | + if (!isRecording) { |
| 18 | + try { |
| 19 | + // Подключаемся к WebSocket серверу |
| 20 | + socket = new WebSocket('ws://192.168.2.109:9002'); |
| 21 | + |
| 22 | + // Получаем доступ к микрофону |
| 23 | + const stream = await navigator.mediaDevices.getUserMedia({ audio: true }); |
| 24 | + const audioContext = new AudioContext({sampleRate: 16000}); |
| 25 | + const source = audioContext.createMediaStreamSource(stream); |
| 26 | + |
| 27 | + // Создаем обработчик аудио данных |
| 28 | + const processor = audioContext.createScriptProcessor(1024, 1, 1); |
| 29 | + |
| 30 | + source.connect(processor); |
| 31 | + processor.connect(audioContext.destination); |
| 32 | + function floatTo16BitPCM(input) { |
| 33 | + const output = new Int16Array(input.length); |
| 34 | + for (let i = 0; i < input.length; i++) { |
| 35 | + output[i] = Math.max(-1, Math.min(1, input[i])) * 0x7FFF; |
| 36 | + } |
| 37 | + return output; |
| 38 | + } |
| 39 | + processor.onaudioprocess = (e) => { |
| 40 | + // Получаем PCM данные |
| 41 | + const input = e.inputBuffer.getChannelData(0); |
| 42 | + const int16Data = floatTo16BitPCM(input); |
| 43 | + |
| 44 | + // Отправляем через WebSocket когда соединение открыто |
| 45 | + if (socket.readyState === WebSocket.OPEN) { |
| 46 | + socket.send(int16Data.buffer); |
| 47 | + } |
| 48 | + }; |
| 49 | + |
| 50 | + statusDiv.textContent = 'Recording...'; |
| 51 | + startBtn.textContent = 'Stop'; |
| 52 | + isRecording = true; |
| 53 | + } catch (err) { |
| 54 | + console.error('Error accessing microphone:', err); |
| 55 | + statusDiv.textContent = 'Error accessing microphone'; |
| 56 | + } |
| 57 | + } else { |
| 58 | + // Остановка записи |
| 59 | + if (socket) socket.close(); |
| 60 | + statusDiv.textContent = 'Stopped'; |
| 61 | + startBtn.textContent = 'Start Mic'; |
| 62 | + isRecording = false; |
| 63 | + } |
| 64 | + }); |
| 65 | + </script> |
| 66 | +</body> |
| 67 | +</html> |
0 commit comments