babylon.audioengine.ts 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. } catch (e) {
  18. this.canUseWebAudio = false;
  19. BABYLON.Tools.Error("Your browser doesn't support Web Audio.");
  20. }
  21. // create a global volume gain node
  22. if (this.canUseWebAudio) {
  23. this.masterGain = this.audioContext.createGain();
  24. this.masterGain.gain.value = 1;
  25. this.masterGain.connect(this.audioContext.destination);
  26. }
  27. }
  28. public dispose() {
  29. if (this.canUseWebAudio) {
  30. if (this._connectedAnalyser) {
  31. this._connectedAnalyser.stopDebugCanvas();
  32. }
  33. this.canUseWebAudio = false;
  34. this.masterGain.disconnect();
  35. this.masterGain = null;
  36. this.audioContext = null;
  37. }
  38. }
  39. public getGlobalVolume(): number {
  40. if (this.canUseWebAudio) {
  41. return this.masterGain.gain.value;
  42. }
  43. else {
  44. return -1;
  45. }
  46. }
  47. public setGlobalVolume(newVolume: number) {
  48. if (this.canUseWebAudio) {
  49. this.masterGain.gain.value = newVolume;
  50. }
  51. }
  52. public connectToAnalyser(analyser: Analyser) {
  53. if (this._connectedAnalyser) {
  54. this._connectedAnalyser.stopDebugCanvas();
  55. }
  56. this._connectedAnalyser = analyser;
  57. if (this.canUseWebAudio) {
  58. this.masterGain.disconnect();
  59. this._connectedAnalyser.connectAudioNodes(this.masterGain, this.audioContext.destination);
  60. }
  61. }
  62. }
  63. }