Advertisement
Guest User

Untitled

a guest
Aug 18th, 2017
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.53 KB | None | 0 0
  1. /**
  2. * @license Copyright 2017 - Chris West - MIT Licensed
  3. * Prototype to easily set the volume (actual and perceived), loudness,
  4. * decibels, and gain value.
  5. */
  6. function MediaElementAmplifier(mediaElem) {
  7. this._context = new (window.AudioContext || window.webkitAudioContext);
  8. this._source = this._context.createMediaElementSource(this._element = mediaElem);
  9. this._source.connect(this._gain = this._context.createGain());
  10. this._gain.connect(this._context.destination);
  11. }
  12. [
  13. 'getContext',
  14. 'getSource',
  15. 'getGain',
  16. 'getElement',
  17. [
  18. 'getVolume',
  19. function(opt_getPerceived) {
  20. return (opt_getPerceived ? this.getLoudness() : 1) * this._element.volume;
  21. }
  22. ],
  23. [
  24. 'setVolume',
  25. function(value, opt_setPerceived) {
  26. this._element.volume = value / (opt_setPerceived ? this.getLoudness() : 1);
  27. }
  28. ],
  29. [ 'getGainValue', function() { return this._gain.gain.value; } ],
  30. [ 'setGainValue', function(value) { this._gain.gain.value = value; } ],
  31. [ 'getDecibels', function() { return 20 * Math.log10(this.getGainValue()); } ],
  32. [ 'setDecibels', function(value) { this.setGainValue(Math.pow(10, value / 20)); } ],
  33. [ 'getLoudness', function() { return Math.pow(2, this.getDecibels() / 10); } ],
  34. [ 'setLoudness', function(value) { this.setDecibels(10 * Math.log2(value)); } ]
  35. ].forEach(function(name, fn) {
  36. if ('string' == typeof name) {
  37. fn = function() { return this[name.replace('get', '').toLowerCase()]; };
  38. }
  39. else {
  40. fn = name[1];
  41. name = name[0];
  42. }
  43. MediaElementAmplifier.prototype[name] = fn;
  44. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement