Change sample rate of AudioContext (getUserMedia)

f.lorenzo picture f.lorenzo · May 4, 2015 · Viewed 23.1k times · Source

Im trying to record a 48000Hz recording via getUserMedia. But without luck. The returned audio MediaStream returns 44100Hz. How can i set this to 48000Hz?

Here are snippets of my code:

var startUsermedia = this.startUsermedia;

            navigator.getUserMedia({ 
                audio: true, 
                //sampleRate: 48000 
            }, startUsermedia, function (e) {
                console.log('No live audio input: ' + e);
            });

The startUsermedia function:

startUsermedia: function (stream) {
            var input = audio_context.createMediaStreamSource(stream);
            console.log('Media stream created.');
            // Uncomment if you want the audio to feedback directly
            //input.connect(audio_context.destination);
            //__log('Input connected to audio context destination.');

            recorder = new Recorder(input);
            console.log('Recorder initialised.');
        },

I tried changing the property sampleRate of the AudioContext, but no luck.

How can i change the sampleRate to 48000Hz?

EDIT : We are also now okay with a flash solution that can record and export wav files at 48000Hz

Answer

basilikum picture basilikum · May 4, 2015

As far as I know, there is no way to change the sample rate within an audio context. The sample rate will usually be the sample rate of your recording device and will stay that way. So you will not be able to write something like this:

var input = audio_context.createMediaStreamSource(stream);
var resampler = new Resampler(44100, 48000);
input.connect(resampler);
resampler.connect(audio_context.destination);

However, if you want to take your audio stream, resample it and then send it to the backend (or do sth. else with it outside of the Web Audio API), you can use an external sample rate converter (e.g. https://github.com/taisel/XAudioJS/blob/master/resampler.js).

   var resampler = new Resampler(44100, 48000, 1, 2229);

   function startUsermedia(stream) {
        var input = audio_context.createMediaStreamSource(stream);
        console.log('Media stream created.');


        recorder = audio_context.createScriptProcessor(2048);
        recorder.onaudioprocess = recorderProcess;
        recorder.connect(audio_context.destination);
    }

    function recorderProcess(e) {
        var buffer = e.inputBuffer.getChannelData(0);
        var resampled = resampler.resampler(buffer);
        //--> do sth with the resampled data for instance send to server
    }