2015-01-08 24 views
18

È possibile accedere al microfono (integrato o ausiliario) da un browser utilizzando JavaScript sul lato client?Accesso al microfono da un browser - Javascript

Idealmente, memorizzerebbe l'audio registrato nel browser. Grazie!

+1

@poisonlocc Check this out: http://www.html5rocks.com/en/tutorials/getusermedia/intro/ – Brad

risposta

20

Qui abbiamo catturare l'audio del microfono come un buffer utilizzando getUserMedia() - nel dominio del tempo e nel dominio della frequenza frammenti di ogni buffer viene stampato (visualizzabile in consolle browser con un colpo Ctrl-Shift-i su Linux)

<html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> 
<title>capture microphone audio into buffer</title> 

<script type="text/javascript"> 


    var webaudio_tooling_obj = function() { 

    var audioContext = new AudioContext(); 

    console.log("audio is starting up ..."); 

    var BUFF_SIZE = 16384; 

    var audioInput = null, 
     microphone_stream = null, 
     gain_node = null, 
     script_processor_node = null, 
     script_processor_fft_node = null, 
     analyserNode = null; 

    if (!navigator.getUserMedia) 
      navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || 
          navigator.mozGetUserMedia || navigator.msGetUserMedia; 

    if (navigator.getUserMedia){ 

     navigator.getUserMedia({audio:true}, 
      function(stream) { 
       start_microphone(stream); 
      }, 
      function(e) { 
      alert('Error capturing audio.'); 
      } 
     ); 

    } else { alert('getUserMedia not supported in this browser.'); } 

    // --- 

    function show_some_data(given_typed_array, num_row_to_display, label) { 

     var size_buffer = given_typed_array.length; 
     var index = 0; 
     var max_index = num_row_to_display; 

     console.log("__________ " + label); 

     for (; index < max_index && index < size_buffer; index += 1) { 

      console.log(given_typed_array[index]); 
     } 
    } 

    function process_microphone_buffer(event) { 

     var i, N, inp, microphone_output_buffer; 

     microphone_output_buffer = event.inputBuffer.getChannelData(0); // just mono - 1 channel for now 

     // microphone_output_buffer <-- this buffer contains current gulp of data size BUFF_SIZE 

     show_some_data(microphone_output_buffer, 5, "from getChannelData"); 
    } 

    function start_microphone(stream){ 

     gain_node = audioContext.createGain(); 
     gain_node.connect(audioContext.destination); 

     microphone_stream = audioContext.createMediaStreamSource(stream); 
     microphone_stream.connect(gain_node); 

     script_processor_node = audioContext.createScriptProcessor(BUFF_SIZE, 1, 1); 
     script_processor_node.onaudioprocess = process_microphone_buffer; 

     microphone_stream.connect(script_processor_node); 

     // --- enable volume control for output speakers 

     document.getElementById('volume').addEventListener('change', function() { 

      var curr_volume = this.value; 
      gain_node.gain.value = curr_volume; 

      console.log("curr_volume ", curr_volume); 
     }); 

     // --- setup FFT 

     script_processor_fft_node = audioContext.createScriptProcessor(2048, 1, 1); 
     script_processor_fft_node.connect(gain_node); 

     analyserNode = audioContext.createAnalyser(); 
     analyserNode.smoothingTimeConstant = 0; 
     analyserNode.fftSize = 2048; 

     microphone_stream.connect(analyserNode); 

     analyserNode.connect(script_processor_fft_node); 

     script_processor_fft_node.onaudioprocess = function() { 

     // get the average for the first channel 
     var array = new Uint8Array(analyserNode.frequencyBinCount); 
     analyserNode.getByteFrequencyData(array); 

     // draw the spectrogram 
     if (microphone_stream.playbackState == microphone_stream.PLAYING_STATE) { 

      show_some_data(array, 5, "from fft"); 
     } 
     }; 
    } 

    }(); // webaudio_tooling_obj = function() 



</script> 

</head> 
<body> 

    <p>Volume</p> 
    <input id="volume" type="range" min="0" max="1" step="0.1" value="0.5"/> 

</body> 
</html> 

Dal momento che questo codice espone i dati microfono come un buffer è possibile aggiungere capacità di streaming utilizzando WebSockets o semplicemente aggregata in un file per il download

noti la chiamata a

var audioContext = new AudioContext(); 

che indica la sua utilizzando il Web Audio API, che viene cotto in tutti i browser moderni (tra cui browser per dispositivi mobili) per fornire una piattaforma audio estremamente potente di cui attingere il microfono non è che un minuscolo frammento

Link ad alcuni Web Audio API documentation

+0

Hi @ Scott-Stensland, questo è grande. Hai scritto questo codice? C'è una fonte originale o un repo o una licenza per questo? Grazie! – binarymax

+4

@binarymax Sì, è il mio codice ... sentitevi liberi di saccheggiare a volontà ... Mi sono insegnato sopra i trucchi mentre scrivevo https://github.com/scottstensland/websockets-streaming-audio che trasmette l'audio dal server tramite websocket per quindi esegui il rendering nel browser utilizzando l'API Web Audio utilizzando un livello interstitial per il webworker per fare da babysitter al traffico di rete ... Ho bisogno di riattivare quel codice ;-) poiché era un esercizio di apprendimento rigoroso –

+0

Qual è un buon modo per imparare tutto questo, io so javascritp e dom. Non conosco l'api audio e tutto ciò che ne consegue come dimensione del buffer, canali, streaming ecc. –

Problemi correlati