HTML5 nagrywanie dźwięku do pliku

Ostatecznie chcę nagrać z mikrofonu użytkownika i przesłać plik na serwer, gdy skończy się. Do tej pory udało mi się zrobić strumień do elementu o następującym kodzie:

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

Jak przejść od tego, do nagrywania do pliku?

Author: Fibericon, 2013-05-07

7 answers

Jest całkiem kompletne demo nagrania dostępne na stronie: http://webaudiodemos.appspot.com/AudioRecorder/index.html

Pozwala na nagrywanie dźwięku w przeglądarce, a następnie daje możliwość eksportu i pobrania tego, co nagrałeś.

Możesz wyświetlić źródło tej strony, aby znaleźć linki do javascript, ale podsumowując, istnieje obiekt Recorder, który zawiera metodę exportWAV i metodę forceDownload.

 90
Author: Brad Montgomery,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-05-11 14:43:10

Poniższy kod jest chroniony prawami autorskimi do Matt Diamond i jest dostępny do użytku na licencji MIT. Oryginalne pliki są tutaj:

Zapisz ten plik i użyj

(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>
 36
Author: Ankit Aranya,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-09-23 10:59:14

Jest to prosty rejestrator i edytor dźwięku JavaScript. Możesz spróbować.

Https://www.danieldemmel.me/JSSoundRecorder/

Można pobrać stąd

Https://github.com/daaain/JSSoundRecorder

 8
Author: jhpratt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-10 23:54:24

Aktualizacja Teraz Chrome obsługuje również API MediaRecorder z wersji v47. To samo, co należy zrobić, to go użyć (zgadywanie natywnej metody nagrywania jest na pewno szybsze niż wokół pracy), API jest naprawdę łatwy w użyciu, i można znaleźć mnóstwo odpowiedzi, Jak przesłać blob na serwer.

Demo - działa w Chrome i Firefoxie, celowo pomijając popychanie Bloba na serwer...

Kod Źródło


Obecnie istnieją trzy sposoby, aby to zrobić:

  1. jako wav [cały kod po stronie klienta, nieskompresowane nagrywanie], możesz sprawdzić -- > Recorderjs . Problem: Rozmiar pliku jest dość duży, wymagana większa przepustowość przesyłania.
  2. jako mp3 [cały kod po stronie klienta, skompresowane nagrywanie], możesz sprawdzić -- > mp3Recorder . Problem: osobiście uważam, że jakość jest zła, również jest ten problem z licencją.
  3. Jako ogg [Klient+ Serwer (node.js) Kod, skompresowane nagrywanie, nieskończone godziny nagrywania bez awarii przeglądarki], możesz sprawdzić -- > recordOpus , albo tylko nagrywanie po stronie klienta, albo łączenie klient-serwer, wybór należy do ciebie.

    Przykład zapisu Ogg (tylko 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 do nagrywania ogg.

 8
Author: mido,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-09 08:02:43

Oto projekt gitHub, który właśnie to robi.

Zapisuje dźwięk z przeglądarki w formacie mp3 i automatycznie zapisuje go na serwerze WWW. https://github.com/Audior/Recordmp3js

Można również zobaczyć szczegółowe wyjaśnienie realizacji: http://audior.ec/blog/recording-mp3-using-only-html5-and-javascript-recordmp3-js/

 5
Author: Remus Negrota,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-09 15:39:29

Możesz użyć Recordmp3js z GitHub, aby spełnić swoje wymagania. Możesz nagrywać z mikrofonu użytkownika, a następnie pobrać plik jako mp3. Na koniec prześlij go na serwer.

Użyłem tego w moim demo. W tej lokalizacji jest już dostępna próbka z kodem źródłowym autora : https://github.com/Audior/Recordmp3js

Demo jest tutaj: http://audior.ec/recordmp3js/

Ale obecnie działa tylko na Chrome i Firefox.

Wydaje się działać dobrze i dość proste. Mam nadzieję, że to pomoże.

 5
Author: Adithya Kumaranchath,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-09 15:58:34

Przesyłanie strumieniowe dźwięku w czasie rzeczywistym bez czekania na zakończenie nagrywania: https://github.com/noamtcohen/AudioStreamer

To strumieniuje dane PCM, ale można zmodyfikować kod do strumieniowania mp3 lub Speex

 2
Author: noamtcohen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-09-03 07:24:54