I am new to JavaScript and I am trying to make an online audio recorder using the getUserMedia API. The problem that I am having is that whenever I try to call navigator.getUserMedia, I am getting an error that the success callback function is undefined, and therefore not a function. It works when I add parentheses after the callback, but then I get an error about an invalid MediaStream source when I call createMediaStreamSource.
I have found some examples that use getUserMedia online, but I am running into the same problem when I try to run them from my computer, even though they clearly work online.
Here is my code below. Thanks!
window.AudioContext = window.AudioContext || window.webkitAudioContext;
var context = new AudioContext();
//tests if browser is compatible with getUserMedia API
function hasGetUserMedia()
{
return !!(navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia);
}
//successful callback for getUserMedia
function gotStream(stream)
{
console.log('Compatible')
//set up microphone input to Web Audio API
var mic = context.createMediaStreamSource(stream);
var filter = context.createBiquadFilter();
//connect
mic.connect(filter);
filter.connect(context.destination);
console.log('Here')
}
//error Callback for getUserMedia
function errorCallback()
{
alert('Error capturing audio');
}
//initial function
function testGetUserMedia()
{
if (!hasGetUserMedia())
{
alert("getUserMedia() is not supported in your browser");
window.close();
}
//if Compatible
getUserMedia({audio:true}, gotStream, errorCallback);
}
window.addEventListener('load', testGetUserMedia);
Firstly, in the code you gave, you are not calling
getUserMedia
on the navigator context (navigator.getUserMedia
), but on thethis
context. Secondly, callingnavigator.getUserMedia
won't be enough, because that isn't browser-specific. I would recommend returning the actualgetUserMedia
function fromhasGetUserMedia
instead of returning a boolean.However, when I fixed those two problems, I had no problem with your code. It ran just fine. As a simple test, I just changed:
to
:: Running on Chrome 37