HTML5将audio录制到文件

我最终想要做的是从用户的麦克风录制,并在完成后将file upload到服务器。 到目前为止,我已经设法使用以下代码创build一个元素stream:

var audio = document.getElementById("audio_preview"); navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia; navigator.getUserMedia({video: false, audio: true}, function(stream) { audio.src = window.URL.createObjectURL(stream); }, onRecordFail); var onRecordFail = function (e) { console.log(e); } 

我该如何去logging到文件?

有一个相当完整的录音演示可在: http : //webaudiodemos.appspot.com/AudioRecorder/index.html

它允许您在浏览器中录制audio,然后让您select导出和下载您录制的内容。

您可以查看该页面的来源以查findJavaScript的链接,但总而言之,有一个Recorder对象包含一个exportWAV方法和一个forceDownload方法。

下面显示的代码版权归Matt Diamond所有,可以在MIT许可下使用。 原始文件在这里:

保存这个文件并使用

 (function(window){ var WORKER_PATH = 'recorderWorker.js'; var Recorder = function(source, cfg){ var config = cfg || {}; var bufferLen = config.bufferLen || 4096; this.context = source.context; this.node = this.context.createJavaScriptNode(bufferLen, 2, 2); var worker = new Worker(config.workerPath || WORKER_PATH); worker.postMessage({ command: 'init', config: { sampleRate: this.context.sampleRate } }); var recording = false, currCallback; this.node.onaudioprocess = function(e){ if (!recording) return; worker.postMessage({ command: 'record', buffer: [ e.inputBuffer.getChannelData(0), e.inputBuffer.getChannelData(1) ] }); } this.configure = function(cfg){ for (var prop in cfg){ if (cfg.hasOwnProperty(prop)){ config[prop] = cfg[prop]; } } } this.record = function(){ recording = true; } this.stop = function(){ recording = false; } this.clear = function(){ worker.postMessage({ command: 'clear' }); } this.getBuffer = function(cb) { currCallback = cb || config.callback; worker.postMessage({ command: 'getBuffer' }) } this.exportWAV = function(cb, type){ currCallback = cb || config.callback; type = type || config.type || 'audio/wav'; if (!currCallback) throw new Error('Callback not set'); worker.postMessage({ command: 'exportWAV', type: type }); } worker.onmessage = function(e){ var blob = e.data; currCallback(blob); } source.connect(this.node); this.node.connect(this.context.destination); //this should not be necessary }; Recorder.forceDownload = function(blob, filename){ var url = (window.URL || window.webkitURL).createObjectURL(blob); var link = window.document.createElement('a'); link.href = url; link.download = filename || 'output.wav'; var click = document.createEvent("Event"); click.initEvent("click", true, true); link.dispatchEvent(click); } window.Recorder = Recorder; })(window); //ADDITIONAL JS recorderWorker.js var recLength = 0, recBuffersL = [], recBuffersR = [], sampleRate; this.onmessage = function(e){ switch(e.data.command){ case 'init': init(e.data.config); break; case 'record': record(e.data.buffer); break; case 'exportWAV': exportWAV(e.data.type); break; case 'getBuffer': getBuffer(); break; case 'clear': clear(); break; } }; function init(config){ sampleRate = config.sampleRate; } function record(inputBuffer){ recBuffersL.push(inputBuffer[0]); recBuffersR.push(inputBuffer[1]); recLength += inputBuffer[0].length; } function exportWAV(type){ var bufferL = mergeBuffers(recBuffersL, recLength); var bufferR = mergeBuffers(recBuffersR, recLength); var interleaved = interleave(bufferL, bufferR); var dataview = encodeWAV(interleaved); var audioBlob = new Blob([dataview], { type: type }); this.postMessage(audioBlob); } function getBuffer() { var buffers = []; buffers.push( mergeBuffers(recBuffersL, recLength) ); buffers.push( mergeBuffers(recBuffersR, recLength) ); this.postMessage(buffers); } function clear(){ recLength = 0; recBuffersL = []; recBuffersR = []; } function mergeBuffers(recBuffers, recLength){ var result = new Float32Array(recLength); var offset = 0; for (var i = 0; i < recBuffers.length; i++){ result.set(recBuffers[i], offset); offset += recBuffers[i].length; } return result; } function interleave(inputL, inputR){ var length = inputL.length + inputR.length; var result = new Float32Array(length); var index = 0, inputIndex = 0; while (index < length){ result[index++] = inputL[inputIndex]; result[index++] = inputR[inputIndex]; inputIndex++; } return result; } function floatTo16BitPCM(output, offset, input){ for (var i = 0; i < input.length; i++, offset+=2){ var s = Math.max(-1, Math.min(1, input[i])); output.setInt16(offset, s < 0 ? s * 0x8000 : s * 0x7FFF, true); } } function writeString(view, offset, string){ for (var i = 0; i < string.length; i++){ view.setUint8(offset + i, string.charCodeAt(i)); } } function encodeWAV(samples){ var buffer = new ArrayBuffer(44 + samples.length * 2); var view = new DataView(buffer); /* RIFF identifier */ writeString(view, 0, 'RIFF'); /* file length */ view.setUint32(4, 32 + samples.length * 2, true); /* RIFF type */ writeString(view, 8, 'WAVE'); /* format chunk identifier */ writeString(view, 12, 'fmt '); /* format chunk length */ view.setUint32(16, 16, true); /* sample format (raw) */ view.setUint16(20, 1, true); /* channel count */ view.setUint16(22, 2, true); /* sample rate */ view.setUint32(24, sampleRate, true); /* byte rate (sample rate * block align) */ view.setUint32(28, sampleRate * 4, true); /* block align (channel count * bytes per sample) */ view.setUint16(32, 4, true); /* bits per sample */ view.setUint16(34, 16, true); /* data chunk identifier */ writeString(view, 36, 'data'); /* data chunk length */ view.setUint32(40, samples.length * 2, true); floatTo16BitPCM(view, 44, samples); return view; } 
 <html> <body> <audio controls autoplay></audio> <script type="text/javascript" src="recorder.js"> </script> <fieldset><legend>RECORD AUDIO</legend> <input onclick="startRecording()" type="button" value="start recording" /> <input onclick="stopRecording()" type="button" value="stop recording and play" /> </fieldset> <script> var onFail = function(e) { console.log('Rejected!', e); }; var onSuccess = function(s) { var context = new webkitAudioContext(); var mediaStreamSource = context.createMediaStreamSource(s); recorder = new Recorder(mediaStreamSource); recorder.record(); // audio loopback // mediaStreamSource.connect(context.destination); } window.URL = window.URL || window.webkitURL; navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia; var recorder; var audio = document.querySelector('audio'); function startRecording() { if (navigator.getUserMedia) { navigator.getUserMedia({audio: true}, onSuccess, onFail); } else { console.log('navigator.getUserMedia not present'); } } function stopRecording() { recorder.stop(); recorder.exportWAV(function(s) { audio.src = window.URL.createObjectURL(s); }); } </script> </body> </html> 

这是一个简单的JavaScript录音机和编辑器。 你可以尝试一下。 http://www.danieldemmel.me/JSSoundRecorder/

可以从这里下载

https://github.com/daaain/JSSoundRecorder

立即更新 Chrome还支持v47版本的MediaRecorder API。 理想的做法是使用它(猜测原生录制方法肯定比工作更快),这个API真的很容易使用,而且你会发现很多关于如何上传服务器的blob的答案。

演示 – 将在Chrome和Firefox中工作,有意无视Blob到服务器…

代码来源


目前有三种方法可以做到这一点:

  1. 作为wav [所有的代码客户端,无压缩录音],你可以检查出 – > Recorderjs 。 问题:文件大小相当大,需要更多的上传带宽。
  2. 作为mp3 [所有代码客户端,压缩录音],你可以检查出 – > mp3Recorder 。 问题:我个人认为质量不好,也有这个许可问题。
  3. 作为ogg [客户端+服务器( node.js )代码,压缩录制,无限制录制,无需浏览器崩溃],您可以查看 – > recordOpus ,无论是客户端录制还是客户端服务器捆绑, 。

    ogg录音的例子(只有Firefox):

     var mediaRecorder = new MediaRecorder(stream); mediaRecorder.start(); // to start recording. ... mediaRecorder.stop(); // to stop recording. mediaRecorder.ondataavailable = function(e) { // do something with the data. } 

    ogg录音的小提琴演示

这是一个gitHub项目。

它以mp3格式logging来自浏览器的audio,并自动将其保存到networking服务器。 https://github.com/nusofthq/Recordmp3js

你也可以查看实现的详细解释: http : //nusofthq.com/blog/recording-mp3-using-only-html5-and-javascript-recordmp3-js/

您可以使用GitHub中的Recordmp3js来实现您的要求。 您可以从用户的麦克风录制,然后将该文件作为mp3。 最后上传到你的服务器。

我在演示中使用了这个。 作者在这个位置已经有一个源代码示例: https : //github.com/nusofthq/Recordmp3js

演示在这里: http : //audior.ec/recordmp3js/

但目前只适用于Chrome和Firefox。

似乎工作很好,很简单。 希望这可以帮助。

实时stream式传输audio,无需等待录音结束: https : //github.com/noamtcohen/AudioStreamer

这streamPCM数据,但你可以修改代码streamMP3或Speex