babylon.audioengine.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. module BABYLON {
  2. export class AudioEngine {
  3. public audioContext: AudioContext = null;
  4. public canUseWebAudio: boolean = false;
  5. public masterGain: GainNode;
  6. constructor() {
  7. // creating the audio context
  8. try {
  9. if (typeof AudioContext !== 'undefined') {
  10. this.audioContext = new AudioContext();
  11. this.canUseWebAudio = true;
  12. } else if (typeof webkitAudioContext !== 'undefined') {
  13. this.audioContext = new webkitAudioContext();
  14. this.canUseWebAudio = true;
  15. }
  16. } catch (e) {
  17. this.canUseWebAudio = false;
  18. BABYLON.Tools.Error("Your browser doesn't support Web Audio.");
  19. }
  20. // create a global volume gain node
  21. if (this.canUseWebAudio) {
  22. this.masterGain = this.audioContext.createGain();
  23. this.masterGain.gain.value = 1;
  24. this.masterGain.connect(this.audioContext.destination);
  25. }
  26. }
  27. public getGlobalVolume(): number {
  28. if (this.canUseWebAudio) {
  29. return this.masterGain.gain.value;
  30. }
  31. else {
  32. return -1;
  33. }
  34. }
  35. public setGlobalVolume(newVolume: number) {
  36. if (this.canUseWebAudio) {
  37. this.masterGain.gain.value = newVolume;
  38. }
  39. }
  40. public connectToAnalyser(analyser: Analyser) {
  41. if (this.canUseWebAudio) {
  42. this.masterGain.disconnect();
  43. analyser.connectAudioNodes(this.masterGain, this.audioContext.destination);
  44. }
  45. }
  46. }
  47. }