GetUserMedia Microphone Example

By Stephen Garside on 5/16/2017

Capturing Microphone input in HTML5 and Javascript has never been easier with GetUserMedia.  With just a few lines of code you can prompt your visitors for permission to capture sound via their microphone, and here is some example code of how to do it:

var audioCapture = (function ()
{
    var init = function ()
    {
        initCapture();
    };
 
    function initCapture()
    {
        var constraints = { audio: true, video: false };
 
        navigator.mediaDevices.getUserMedia(constraints).then(function (stream)
        {
            var audio = document.getElementById('audioCapture');
            audio.srcObject = stream;
            audio.play();
        }).catch(function (err)
        {
            console.log(err);
        });
    }
 
    return {
        Init: init
    }
})();

This encapsulated code snippet can form the basis of a much more functionally rich class. Alongside it you will need to add an <audio> tag to your html and also a script to initiate the class as so:-

<audio id="audioCapture"></audio>
<script>
    audioCapture.Init();
</script>

At the time of writing this GetUserMedia microphone example works in all major browsers including Edge, Chrome and Firefox so there are no excuse not to try it!  You can also use GetUserMedia to capture camera, video and webcam input using code similar to above.

Share this article...
Join the Discussion...