babylon.audioEngine.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. module BABYLON {
  2. export class AudioEngine {
  3. public audioContext: AudioContext = null;
  4. public canUseWebAudio: boolean = false;
  5. public masterGain: GainNode;
  6. private _connectedAnalyser: Analyser;
  7. public WarnedWebAudioUnsupported: boolean = false;
  8. constructor() {
  9. // creating the audio context
  10. try {
  11. if (typeof AudioContext !== 'undefined') {
  12. this.audioContext = new AudioContext();
  13. this.canUseWebAudio = true;
  14. } else if (typeof webkitAudioContext !== 'undefined') {
  15. this.audioContext = new webkitAudioContext();
  16. this.canUseWebAudio = true;
  17. }
  18. } catch (e) {
  19. this.canUseWebAudio = false;
  20. Tools.Error("Web Audio: " + e.message);
  21. }
  22. // create a global volume gain node
  23. if (this.canUseWebAudio) {
  24. this.masterGain = this.audioContext.createGain();
  25. this.masterGain.gain.value = 1;
  26. this.masterGain.connect(this.audioContext.destination);
  27. }
  28. }
  29. public dispose() {
  30. if (this.canUseWebAudio) {
  31. if (this._connectedAnalyser) {
  32. this._connectedAnalyser.stopDebugCanvas();
  33. this._connectedAnalyser.dispose();
  34. this.masterGain.disconnect();
  35. this.masterGain.connect(this.audioContext.destination);
  36. this._connectedAnalyser = null;
  37. }
  38. this.masterGain.gain.value = 1;
  39. }
  40. this.WarnedWebAudioUnsupported = false;
  41. }
  42. public getGlobalVolume(): number {
  43. if (this.canUseWebAudio) {
  44. return this.masterGain.gain.value;
  45. }
  46. else {
  47. return -1;
  48. }
  49. }
  50. public setGlobalVolume(newVolume: number) {
  51. if (this.canUseWebAudio) {
  52. this.masterGain.gain.value = newVolume;
  53. }
  54. }
  55. public connectToAnalyser(analyser: Analyser) {
  56. if (this._connectedAnalyser) {
  57. this._connectedAnalyser.stopDebugCanvas();
  58. }
  59. this._connectedAnalyser = analyser;
  60. if (this.canUseWebAudio) {
  61. this.masterGain.disconnect();
  62. this._connectedAnalyser.connectAudioNodes(this.masterGain, this.audioContext.destination);
  63. }
  64. }
  65. }
  66. }