HTML5录制音频到文件

blmhpbnm  于 2023-10-14  发布在  HTML5
关注(0)|答案(9)|浏览(227)

我最终想做的是从用户的麦克风记录,并在他们完成后将文件上传到服务器。到目前为止,我已经成功地使用以下代码创建了一个元素的流:

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);
}

我如何从这一点,记录到一个文件?

wf82jlnq

wf82jlnq1#

有一个相当完整的录音演示可在:http://webaudiodemos.appspot.com/AudioRecorder/index.html
它允许您在浏览器中录制音频,然后为您提供导出和下载录制内容的选项。
您可以查看该页面的源代码以找到指向JavaScript的链接,但总结一下,有一个Recorder对象,它包含一个exportWAV方法和一个forceDownload方法。

ssm49v7z

ssm49v7z2#

下面显示的代码版权归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.createScriptProcessor(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>
mi7gmzs6

mi7gmzs63#

更新现在Chrome也支持v47的MediaRecorder API。同样的事情要做的是使用它(猜测本机记录方法肯定会比变通方法更快),API真的很容易使用,你会发现关于如何为服务器上传一个blob的答案。

Demo-可以在Chrome和Firefox中工作,故意忽略了将blob推送到服务器.
Code Source
目前,有三种方法可以做到这一点:
1.作为wav [所有代码客户端,未压缩录制],可以查看--> Recorderjs。问题:文件太大,需要更多的上传带宽。
1.作为mp3 [所有代码客户端,压缩记录],可以查看--> mp3Recorder.问题:就我个人而言,我觉得质量不好,也有这个许可证的问题。
1.作为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.
}

Fiddle Demo用于ogg记录。

goqiplq2

goqiplq24#

这是一个简单的JavaScript录音机和编辑器。你可以试试。
https://www.danieldemmel.me/JSSoundRecorder/
可以从这里下载**
https://github.com/daaain/JSSoundRecorder

olhwl3o2

olhwl3o25#

这个问题很老,许多答案在当前版本的浏览器中不受支持。我尝试使用简单的htmlcssjs创建音频记录器。我进一步在electron中使用相同的代码来制作一个跨平台应用程序。

<html>
  <head>
    <title>Recorder App</title>
    
  </head>
  <h2>Recorder App</h2>
  <p>
    <button type="button" id="record">Record</button>
    <button type="button" id="stopRecord" disabled>Stop</button>
  </p>
  <p>
    <audio id="recordedAudio"></audio>        
  </p>

  <script> 
    navigator.mediaDevices.getUserMedia({audio:true})
    .then(stream => {handlerFunction(stream)})

    function handlerFunction(stream) {
      rec = new MediaRecorder(stream);
      rec.ondataavailable = e => {
        audioChunks.push(e.data);
        if (rec.state == "inactive"){
          let blob = new Blob(audioChunks,{type:'audio/mp3'});
          recordedAudio.src = URL.createObjectURL(blob);
          recordedAudio.controls=true;
          recordedAudio.autoplay=true;
          sendData(blob)
          }
        }
      }
    
    function sendData(data) {}
      record.onclick = e => {
        record.disabled = true;
        record.style.backgroundColor = "blue"
        stopRecord.disabled=false;
        audioChunks = [];
        rec.start();
        }
      stopRecord.onclick = e => {
        record.disabled = false;
        stop.disabled=true;
        record.style.backgroundColor = "red"
        rec.stop();
        }
  </script>
</html>

上面的代码可以在Windows 10、Mac、Linux中运行,当然,也可以在谷歌Chrome和火狐上运行。

6kkfgxo0

6kkfgxo06#

您可以使用GitHub中的Recordmp3js来实现您的要求。您可以从用户的麦克风录制,然后将文件作为mp3。最后上传到你的服务器。
我在我的demo中使用了这个。已经有一个示例与源代码由作者在这个位置:https://github.com/Audior/Recordmp3js
demo在这里:http://audior.ec/recordmp3js/
但目前仅适用于Chrome和Firefox。
似乎工作得很好,很简单。希望这对你有帮助。

q1qsirdb

q1qsirdb7#

这里有一个gitHub项目可以做到这一点。
它以mp3格式记录浏览器中的音频,并自动将其保存到Web服务器。https://github.com/Audior/Recordmp3js
您还可以查看实现的详细说明:http://audior.ec/blog/recording-mp3-using-only-html5-and-javascript-recordmp3-js/

7ivaypg9

7ivaypg98#

实时流式传输音频,无需等待录制结束:https://github.com/noamtcohen/AudioStreamer
这将传输PCM数据,但您可以修改代码以传输mp3或Speex

oug3syen

oug3syen9#

如果你只需要wav文件格式,你可以使用这个npm包,不需要做任何修改。https://www.npmjs.com/package/extendable-media-recorder

import { MediaRecorder, register } from 'extendable-media-recorder';
import { connect } from 'extendable-media-recorder-wav-encoder';

await register(await connect());

const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
const mediaRecorder = new MediaRecorder(stream, { mimeType: 'audio/wav' });

相关问题