Javascript 录制麦克风声音
需求: PC端录制声音,通过websocket保存到服务器
服务端代码
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
| const WebSocket = require('ws') const fs = require('fs')
const ws = new WebSocket.Server({ port: 4000 })
ws.on('connection', function (inst) { inst.on('message', function (msg, isBinary) { if (isBinary) { console.log('message') const time = new Date().getTime() fs.writeFile('audio/' + time + '.webm', msg, 'binary', (err) => { if (err) { console.log(err) } }) return } const req = JSON.parse(msg.toString()) if (req.connectionId) { inst.send( JSON.stringify({ code: 0, message: 'success', }) ) } }) inst.on('close', function (code) { console.log('close', code) }) })
|
客户端代码
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
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style type="text/css"> button { cursor: pointer; display: inline-block; width: 120px; line-height: 32px; } </style> </head> <body> <button id="start">开始</button> <button id="stop">结束</button> <script> const btn1 = document.getElementById('start') const btn2 = document.getElementById('stop') let chunks = [] let ws, recorder, timer, streams btn2.disabled = true btn1.addEventListener('click', () => { navigator.mediaDevices.getUserMedia({ audio: true, video: false }).then((stream) => { streams = stream createWs() }) }) btn2.addEventListener('click', () => { if (timer) { clearInterval(timer) timer = null } if (recorder) { recorder.stop() recorder = null } if (ws) { ws.close() ws = null } if (streams) { streams.getTracks().forEach((track) => track.stop()) streams = null } btn2.disabled = true }) function createWs() { ws = new WebSocket('ws://127.0.0.1:4000') ws.onopen = () => { console.log('onopen') ws.send(JSON.stringify({ connectionId: '11111111' })) initAudio() } ws.onmessage = (data) => { const res = JSON.parse(data.data) if (res.code !== 0) { return } console.log('onmessage', res) btn2.disabled = false timer = setInterval(() => { sendData() }, 2000) } ws.onerror = (err) => { console.log('onerror', err) } } function sendData() { recorder.stop() setTimeout(() => { if (recorder) { recorder.start() } }, 100) } function initAudio() { recorder = new MediaRecorder(streams) // 仅在chrome浏览器测试通过,Safari录制不到声音 recorder.ondataavailable = (e) => { chunks.push(e.data) } recorder.onstop = () => { if (!ws) { return } const data = new Blob(chunks) ws.send(data) chunks = [] } recorder.start() } </script> </body> </html>
|