Last active
September 11, 2015 19:05
-
-
Save belackriv/94f9e1fb7e04ca76b2c3 to your computer and use it in GitHub Desktop.
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
var SpectrumDrawer = function(buffer){ | |
this.buffer = buffer; | |
this.bufferPosition = 0; | |
this.bufferLength = this.buffer.length; | |
var pixelWidth = $('#wave').width(); | |
this.sampleBufferLength = Math.floor(this.bufferLength / pixelWidth); | |
$('#spectrum').width(pixelWidth); | |
$('#spectrum').height($('#wave').height()); | |
this.spectrumCanvas = $('#spectrum').get(0); | |
this.ctx = this.spectrumCanvas.getContext('2d'); | |
this.ctx.fillStyle = '#f00'; | |
this.ctx.font = 'bold 12px sans-serif'; | |
this.ctx.textBaseline = 'bottom'; | |
this.drawSpectrum = function(){ | |
var dataArray = new Uint8Array(this.offlineAnalyser.frequencyBinCount); | |
this.offlineAnalyser.getByteFrequencyData(dataArray); | |
this.ctx.clearRect(0, 0, this.spectrumCanvas.width, this.spectrumCanvas.height); | |
var percent = this.bufferPosition/this.bufferLength*100; | |
this.ctx.fillText(this.bufferPosition+' / '+this.bufferLength+'('+percent+'%)', this.bufferPosition/this.sampleBufferLength, 100); | |
this.run(); | |
}; | |
this.getFrequencyData = function(smallBuffer){ | |
var that = this; | |
var offlineAc = new OfflineAudioContext( | |
smallBuffer.numberOfChannels, | |
smallBuffer.length, | |
smallBuffer.sampleRate | |
); | |
this.offlineAnalyser = offlineAc.createAnalyser(); | |
var offlineSource = offlineAc.createBufferSource(); | |
offlineSource.buffer = smallBuffer; | |
offlineSource.connect(this.offlineAnalyser); | |
this.offlineAnalyser.connect(offlineAc.destination); | |
offlineSource.start(); | |
offlineAc.startRendering().then(function(){ | |
that.drawSpectrum(); | |
}); | |
}; | |
this.run = function(){ | |
if(this.bufferPosition < this.bufferLength){ | |
var audioCtx = new AudioContext(); | |
var sampleBuffer = audioCtx.createBuffer(this.buffer.numberOfChannels, this.sampleBufferLength, this.buffer.sampleRate); | |
var bufferArray = null; | |
for(var c = 0; c < this.buffer.numberOfChannels; c++){ | |
bufferArray = this.buffer.getChannelData(c); | |
bufferArray = bufferArray.slice(this.bufferPosition, this.bufferPosition + this.sampleBufferLength); | |
sampleBuffer.copyToChannel(bufferArray, c); | |
} | |
this.getFrequencyData(sampleBuffer); | |
this.bufferPosition = this.bufferPosition + this.sampleBufferLength; | |
audioCtx.close(); | |
if(this.bufferPosition/this.bufferLength > .6){ | |
var pause; | |
} | |
} | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment