Capturing audio over the microphone via Javascript or HTML

Asked

Viewed 6,863 times

8

I need to capture microphone audio and record to file. Send to PHP server. As I do, in the examples I saw here, I didn’t notice how to record the sound files.

  • 1

    Here you go an interesting tutorial (in English). I will take the main points and assemble a response, unless someone does it first... : P

  • Here’s another one: http://creativejs.com/2012/03/getting-started-with-getusermedia/. Vai fundo @mgibsonbr, I’m out of time...

  • 1

    Tip: ask the question the examples you have already tested. This prevents us from suggesting things you have already discarded.

  • 1

    Apparently, both linked tutorials cover only capture audio/video and show in one element on the page itself. Saving is a little more complicated... Before answering, a question: do you want to save this on the server, or simply send it to another user? (e.g., one talks in your browser, the other listens in another browser) The solution is quite different for one case or another.

  • Related question (duplicate?): http://answall.com/questions/11640/howto capture audio-do-microfone-usando-api-de-audio-do-html5

  • Sorry for the delay. Mto thanks for the tips. I actually tested many examples that I found here on Stack and other sites. But none made it possible to capture the audio and upload to a file server (PHP).

Show 1 more comment

2 answers

4

This can be done through Media Capture and Streams, when supported (Firefox, Chrome, and Opera support; Internet Explorer, I’m afraid not yet).

First, look for the function getUserMedia (some browsers/browser versions may use a slightly different name, but the functionality is the same):

var gum = navigator.getUserMedia || 
          navigator.webkitGetUserMedia ||
          navigator.mozGetUserMedia || 
          navigator.msGetUserMedia;

Next, you need the user’s permission to access your devices (microphone, but also camera or other):

function sucesso(localMediaStream) { ... }
function erro(e) { ... }

gum({ video:false, audio:true }, sucesso, erro);

Source: that article (in English)

If the user grants this permission, you will have access to an object MediaStream. Normally you would associate this stream with an element <audio> (to display back to the user) or use Webrtc to send the audio to another user (such as a phone), but in this case, what you want is to record on the server, right?

One option is to use the library Recorder.js. I’ll show you how to send the recording to the server in the format WAV, on the basis of in this example of the library itself and in that reply in Soen:

var recorder = null;
 var AC = window.AudioContext || window.webkitAudioContext;
var audio_context = new AC();

function sucesso(localMediaStream) {
    var input = audio_context.createMediaStreamSource(localMediaStream);
    input.connect(audio_context.destination);
    recorder = new Recorder(input);
    recorder.record();
}

// Quando quiser parar de gravar e enviar; associe essa função a um botão, por exemplo
function enviar() {
    recorder.stop();
    recorder.exportWAV(function (blob) {
        // Envia ao servidor usando Ajax (assíncrono)
        var xhr = new XMLHttpRequest();
        xhr.open('POST', '/upload.php', true);
        xhr.send(blob);
    });
}

I have no way to test this solution at this time (1. my computer has no microphone; 2. I would need to test server-side receiving), but as soon as I can assemble a concrete example put here.


P.S. I believe that Internet Explorer offers an alternative way to do this (I know they have their proprietary features), but I don’t know any.

0

I am using these below, but I can’t pause, write only WAV (mto large file size) and not always open the machine Microphone.

<html>
<head>
    <meta name='author' content='Sajith Amma' /> 
    <script src='jquery.min.js'> </script>
    <script src='jRecorder.js'> </script>
    <!--<title>jRecorder Example</title>  -->
    <style>
        li {display:inline; margin-right:10px;}
    </style> 
</head>
<body> 
    <script>
    $.jRecorder({
        host : 'http://eficazlaudos.com/laudo_voz/acceptfile.php?filename=".$row2['id_lista_trab'].".wav&id_lanca=h71' ,  //replace with your server path please
        callback_started_recording: function(){callback_started(); },
        callback_stopped_recording: function(){callback_stopped(); },
        callback_activityLevel: function(level){callback_activityLevel(level); },
        callback_activityTime: function(time){callback_activityTime(time); },
        callback_finished_sending: function(time){ callback_finished_sending() },
        swf_path : 'jRecorder.swf',
    });
    </script>
</div>
<div style='background-color: #eeeeee;border:1px solid #cccccc'>
    Time: <span id='time'>00:00</span>
</div>
<div>
    Level: <span id='level'></span>
</div>  
<div id='levelbase' style='width:200px;height:20px;background-color:#ffff00'>
    <div id='levelbar' style='height:19px; width:2px;background-color:red'>
    </div>
</div>
<div>
    Status: <span id='status'></status>
</div>  
<div>
    <input type='button' id='record' value='Gravar' style='color:red'>  

    <!--
    <p>
        This Record button trigger the record event. See the javascript example in the bottom of the page. (View Source in your browser).  
        <pre>
            $('#record').click(function() {            
                $.jRecorder.record(30); //record up to 30 sec and stops automatically               
            });
        </pre>
    </p>
    <hr/>
    -->

    <input type='button' id='stop' value='Parar'>    
    <!--
    <p>
        This Stop button trigger the stop record event. 
        <pre>
            Onclick of this button trigger  $.jRecorder.sendData() which send the data to the Server
        </pre>
    </p>
    <hr/>
    -->

    <input type='button' id='send' value='Enviar voz'>
    <!--
    <p>This SendData button trigger the sendData event to flash to send the wav data to Server (configured in the host parameter).
        <hr/>
        <pre>
            $('#stop').click(function(){            
                $.jRecorder.stop();               
            });
        </pre>
    </p>
    <hr/>
    -->

</div>

<!--
<p>
    Time area is used to update the time. There is an event Listener which update the recording time dynamically.
   <pre>
       callback_activityTime: function(time){callback_activityTime(time);  //see the initialisation

       //function callback
       function callback_activityTime(time) {
           $('#time').html(time);
       }
   </pre>  
</p>
--> 

</body>
</html>

<script type='text/javascript'>
    $('#record').click(function(){                    
        $.jRecorder.record(30);                    
    });           
    $('#stop').click(function(){                
        $.jRecorder.stop();
    });
    $('#send').click(function() {
        $.jRecorder.sendData();
    });
    function callback_finished() {
        $('#status').html('Recording is finished');
    }
    function callback_started() {
        $('#status').html('Recording is started');
    }
    function callback_error(code) {
        $('#status').html('Error, code:' + code);
    }
    function callback_stopped() {
        $('#status').html('Stop request is accepted');
    }
    function callback_finished_recording() {
        $('#status').html('Recording event is finished');
    }
    function callback_finished_sending() {
        $('#status').html('File has been sent to server mentioned as host parameter');
    }
    function callback_activityLevel(level) {
        $('#level').html(level);
        if(level == -1) {
            $('#levelbar').css('width',  '2px');
        } else {
            $('#levelbar').css('width', (level * 2)+ 'px');
        }
    }
    function callback_activityTime(time) {
        //$('.flrecorder').css('width', '1px'); 
        //$('.flrecorder').css('height', '1px'); 
        $('#time').html(time);
    }
</script>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.