babylon.audioengine.ts 2.5 KB

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