babylon.audioEngine.ts 3.0 KB

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