babylon.audioEngine.js 3.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. var BABYLON;
  2. (function (BABYLON) {
  3. var AudioEngine = (function () {
  4. function AudioEngine() {
  5. this._audioContext = null;
  6. this._audioContextInitialized = false;
  7. this.canUseWebAudio = false;
  8. this.WarnedWebAudioUnsupported = false;
  9. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  10. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  11. this.canUseWebAudio = true;
  12. }
  13. }
  14. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  15. get: function () {
  16. if (!this._audioContextInitialized) {
  17. this._initializeAudioContext();
  18. }
  19. return this._audioContext;
  20. },
  21. enumerable: true,
  22. configurable: true
  23. });
  24. AudioEngine.prototype._initializeAudioContext = function () {
  25. try {
  26. if (this.canUseWebAudio) {
  27. this._audioContext = new AudioContext();
  28. // create a global volume gain node
  29. this.masterGain = this._audioContext.createGain();
  30. this.masterGain.gain.value = 1;
  31. this.masterGain.connect(this._audioContext.destination);
  32. this._audioContextInitialized = true;
  33. }
  34. }
  35. catch (e) {
  36. this.canUseWebAudio = false;
  37. BABYLON.Tools.Error("Web Audio: " + e.message);
  38. }
  39. };
  40. AudioEngine.prototype.dispose = function () {
  41. if (this.canUseWebAudio && this._audioContextInitialized) {
  42. if (this._connectedAnalyser) {
  43. this._connectedAnalyser.stopDebugCanvas();
  44. this._connectedAnalyser.dispose();
  45. this.masterGain.disconnect();
  46. this.masterGain.connect(this._audioContext.destination);
  47. this._connectedAnalyser = null;
  48. }
  49. this.masterGain.gain.value = 1;
  50. }
  51. this.WarnedWebAudioUnsupported = false;
  52. };
  53. AudioEngine.prototype.getGlobalVolume = function () {
  54. if (this.canUseWebAudio && this._audioContextInitialized) {
  55. return this.masterGain.gain.value;
  56. }
  57. else {
  58. return -1;
  59. }
  60. };
  61. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  62. if (this.canUseWebAudio && this._audioContextInitialized) {
  63. this.masterGain.gain.value = newVolume;
  64. }
  65. };
  66. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  67. if (this._connectedAnalyser) {
  68. this._connectedAnalyser.stopDebugCanvas();
  69. }
  70. if (this.canUseWebAudio && this._audioContextInitialized) {
  71. this._connectedAnalyser = analyser;
  72. this.masterGain.disconnect();
  73. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  74. }
  75. };
  76. return AudioEngine;
  77. })();
  78. BABYLON.AudioEngine = AudioEngine;
  79. })(BABYLON || (BABYLON = {}));