Created
November 8, 2015 08:06
-
-
Save jhiswin/b88ecf7900b76810429b to your computer and use it in GitHub Desktop.
native audio resampler use OfflineAudioContext
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function supportedSampleRates() { | |
return [4000, 8000, 16000, 32000, 44100, 48000, 96000].filter(supportsSampleRate); | |
} | |
function supportsSampleRate(sampleRate) { | |
try { | |
var l = new OfflineAudioContext(1, sampleRate, sampleRate); | |
return true; | |
} | |
catch(e){ | |
return false; | |
} | |
return true; | |
} | |
function f2i(floats){ | |
var ints=[]; | |
var count = floats.length; | |
for (var i = 0; i < count; i++) { | |
ints[i] = floats[i] < 0 ? floats[i] * 32768 : floats[i] * 32767; | |
} | |
return ints; | |
} | |
/** | |
* Resample using OfflineAudioContext | |
*/ | |
function OACX(channels, inBuffer, inNumSamples, inSampleRate, outSampleRate, cb){ | |
var o = new OfflineAudioContext(channels, inNumSamples, outSampleRate); | |
// create audio buffer | |
var b = o.createBuffer(channels, inNumSamples, inSampleRate); | |
// copy data | |
for (var channel = 0; channel < channels; channel++) { | |
var buf = b.getChannelData(channel); | |
for (var i = 0; i < durationInSamples; i++) { | |
buf[i] = inBuffer[i]; | |
} | |
} | |
//b.getChannelData(0).set(inBuffer); | |
/* Play it from the beginning. */ | |
var source = o.createBufferSource(); | |
source.buffer = b; | |
source.start(0); | |
o.oncomplete = function(audiobuffer) { | |
/* audiobuffer contains resampled audio, use | |
* audiobuffer.getChannelData(x) to get an ArrayBuffer for | |
* channel x. | |
*/ | |
cb(audiobuffer); | |
} | |
/* Start rendering as fast as the machine can. */ | |
o.startRendering(); | |
} |
I believe you need to connect source
to offline context
source.connect(o.destination);
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
durationInSamples
is not defined. I suppose it is same asinNumSamples
?