You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

local_stats.js 2.6KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /**
  2. * Provides statistics for the local stream.
  3. */
  4. var LocalStatsCollector = (function() {
  5. /**
  6. * Size of the webaudio analizer buffer.
  7. * @type {number}
  8. */
  9. var WEBAUDIO_ANALIZER_FFT_SIZE = 512;
  10. /**
  11. * Value of the webaudio analizer smoothing time parameter.
  12. * @type {number}
  13. */
  14. var WEBAUDIO_ANALIZER_SMOOTING_TIME = 0.1;
  15. /**
  16. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  17. *
  18. * @param stream the local stream
  19. * @param interval stats refresh interval given in ms.
  20. * @param {function(LocalStatsCollector)} updateCallback the callback called on stats
  21. * update.
  22. * @constructor
  23. */
  24. function LocalStatsCollectorProto(stream, interval, updateCallback) {
  25. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  26. this.stream = stream;
  27. this.intervalId = null;
  28. this.intervalMilis = interval;
  29. this.updateCallback = updateCallback;
  30. this.audioLevel = 0;
  31. }
  32. /**
  33. * Starts the collecting the statistics.
  34. */
  35. LocalStatsCollectorProto.prototype.start = function () {
  36. if (!window.AudioContext)
  37. return;
  38. var context = new AudioContext();
  39. var analyser = context.createAnalyser();
  40. analyser.smoothingTimeConstant = WEBAUDIO_ANALIZER_SMOOTING_TIME;
  41. analyser.fftSize = WEBAUDIO_ANALIZER_FFT_SIZE;
  42. var source = context.createMediaStreamSource(this.stream);
  43. source.connect(analyser);
  44. var self = this;
  45. this.intervalId = setInterval(
  46. function () {
  47. var array = new Uint8Array(analyser.frequencyBinCount);
  48. analyser.getByteFrequencyData(array);
  49. self.audioLevel = FrequencyDataToAudioLevel(array);
  50. self.updateCallback(self);
  51. },
  52. this.intervalMilis
  53. );
  54. };
  55. /**
  56. * Stops collecting the statistics.
  57. */
  58. LocalStatsCollectorProto.prototype.stop = function () {
  59. if (this.intervalId) {
  60. clearInterval(this.intervalId);
  61. this.intervalId = null;
  62. }
  63. };
  64. /**
  65. * Converts frequency data array to audio level.
  66. * @param array the frequency data array.
  67. * @returns {number} the audio level
  68. */
  69. var FrequencyDataToAudioLevel = function (array) {
  70. var maxVolume = 0;
  71. var length = array.length;
  72. for (var i = 0; i < length; i++) {
  73. if (maxVolume < array[i])
  74. maxVolume = array[i];
  75. }
  76. return maxVolume / 255;
  77. };
  78. return LocalStatsCollectorProto;
  79. })();