97 lines
2.6 KiB
JavaScript
97 lines
2.6 KiB
JavaScript
/**
|
|
* Provides statistics for the local stream.
|
|
*/
|
|
var LocalStatsCollector = (function() {
|
|
/**
|
|
* Size of the webaudio analizer buffer.
|
|
* @type {number}
|
|
*/
|
|
var WEBAUDIO_ANALIZER_FFT_SIZE = 512;
|
|
|
|
/**
|
|
* Value of the webaudio analizer smoothing time parameter.
|
|
* @type {number}
|
|
*/
|
|
var WEBAUDIO_ANALIZER_SMOOTING_TIME = 0.1;
|
|
|
|
/**
|
|
* <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
|
|
*
|
|
* @param stream the local stream
|
|
* @param interval stats refresh interval given in ms.
|
|
* @param {function(LocalStatsCollector)} updateCallback the callback called on stats
|
|
* update.
|
|
* @constructor
|
|
*/
|
|
function LocalStatsCollectorProto(stream, interval, updateCallback) {
|
|
window.AudioContext = window.AudioContext || window.webkitAudioContext;
|
|
this.stream = stream;
|
|
this.intervalId = null;
|
|
this.intervalMilis = interval;
|
|
this.updateCallback = updateCallback;
|
|
this.audioLevel = 0;
|
|
}
|
|
|
|
|
|
/**
|
|
* Starts the collecting the statistics.
|
|
*/
|
|
LocalStatsCollectorProto.prototype.start = function () {
|
|
if (!window.AudioContext)
|
|
return;
|
|
|
|
var context = new AudioContext();
|
|
var analyser = context.createAnalyser();
|
|
analyser.smoothingTimeConstant = WEBAUDIO_ANALIZER_SMOOTING_TIME;
|
|
analyser.fftSize = WEBAUDIO_ANALIZER_FFT_SIZE;
|
|
|
|
|
|
var source = context.createMediaStreamSource(this.stream);
|
|
source.connect(analyser);
|
|
|
|
|
|
var self = this;
|
|
|
|
this.intervalId = setInterval(
|
|
function () {
|
|
var array = new Uint8Array(analyser.frequencyBinCount);
|
|
analyser.getByteFrequencyData(array);
|
|
self.audioLevel = FrequencyDataToAudioLevel(array);
|
|
self.updateCallback(self);
|
|
},
|
|
this.intervalMilis
|
|
);
|
|
|
|
}
|
|
|
|
/**
|
|
* Stops collecting the statistics.
|
|
*/
|
|
LocalStatsCollectorProto.prototype.stop = function () {
|
|
if (this.intervalId) {
|
|
clearInterval(this.intervalId);
|
|
this.intervalId = null;
|
|
}
|
|
}
|
|
|
|
|
|
/**
|
|
* Converts frequency data array to audio level.
|
|
* @param array the frequency data array.
|
|
* @returns {number} the audio level
|
|
*/
|
|
var FrequencyDataToAudioLevel = function (array) {
|
|
var maxVolume = 0;
|
|
|
|
var length = array.length;
|
|
|
|
for (var i = 0; i < length; i++) {
|
|
if (maxVolume < array[i])
|
|
maxVolume = array[i];
|
|
}
|
|
|
|
return maxVolume / 255;
|
|
}
|
|
|
|
return LocalStatsCollectorProto;
|
|
})(); |