Last active
September 15, 2015 21:28
-
-
Save lislis/ccdeb9be130c015de1e7 to your computer and use it in GitHub Desktop.
analyse a sound file and play it after that
This file contains hidden or 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
offlineCtx = new OfflineAudioContext(1, 44100 * 60, 44100); | |
offlineAnalyser = offlineCtx.createAnalyser(); | |
offlineAnalyser.fftSize = 4096; | |
offlineProcessor = offlineCtx.createScriptProcessor(16384, 1, 1); | |
offlineProcessor.connect(offlineCtx.destination); | |
offlineSource = offlineCtx.createBufferSource(); | |
offlineFFTArray = []; | |
songToPlay = 'guitar-loop.wav'; | |
playCtx = new AudioContext(); | |
playSource = playCtx.createBufferSource(); | |
playGain = playCtx.createGain(); | |
playGain.gain.value = 1; | |
playSource.connect(playGain); | |
playGain.connect(playCtx.destination); | |
function prepareOfflineData() { | |
var request = new XMLHttpRequest(); | |
request.open('GET', songToPlay, true); | |
request.responseType = 'arraybuffer'; | |
request.onload = function() { | |
var audioData = request.response; | |
offlineCtx.decodeAudioData(audioData, function(buffer) { | |
var decodedOfflineBuffer = buffer; | |
offlineSource.buffer = decodedOfflineBuffer; | |
offlineSource.connect(offlineAnalyser); | |
offlineAnalyser.connect(offlineProcessor); | |
offlineProcessor.onaudioprocess = function(e){ | |
var data = new Uint8Array(offlineAnalyser.frequencyBinCount); | |
offlineAnalyser.getByteFrequencyData(data); | |
offlineFFTArray.push(data); | |
} | |
offlineSource.start(); | |
offlineCtx.startRendering().then(function(renderedBuffer) { | |
playSource.buffer = offlineSource.buffer; | |
playSource.start(); | |
}).catch(function(err) { | |
console.log('Rendering failed: ' + err); | |
}); | |
}); | |
} | |
request.send(); | |
} | |
prepareOfflineData(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment