audioSceneComponent.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. import { Sound } from "./sound";
  2. import { SoundTrack } from "./soundTrack";
  3. import { Engine } from "../Engines/engine";
  4. import { Camera } from "../Cameras/camera";
  5. import { Nullable } from "../types";
  6. import { Matrix, Vector3 } from "../Maths/math.vector";
  7. import { SceneComponentConstants, ISceneSerializableComponent } from "../sceneComponent";
  8. import { Scene } from "../scene";
  9. import { AbstractScene } from "../abstractScene";
  10. import { AssetContainer } from "../assetContainer";
  11. import "./audioEngine";
  12. // Adds the parser to the scene parsers.
  13. AbstractScene.AddParser(SceneComponentConstants.NAME_AUDIO, (parsedData: any, scene: Scene, container: AssetContainer, rootUrl: string) => {
  14. // TODO: add sound
  15. var loadedSounds: Sound[] = [];
  16. var loadedSound: Sound;
  17. container.sounds = container.sounds || [];
  18. if (parsedData.sounds !== undefined && parsedData.sounds !== null) {
  19. for (let index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  20. var parsedSound = parsedData.sounds[index];
  21. if (Engine.audioEngine.canUseWebAudio) {
  22. if (!parsedSound.url) { parsedSound.url = parsedSound.name; }
  23. if (!loadedSounds[parsedSound.url]) {
  24. loadedSound = Sound.Parse(parsedSound, scene, rootUrl);
  25. loadedSounds[parsedSound.url] = loadedSound;
  26. container.sounds.push(loadedSound);
  27. }
  28. else {
  29. container.sounds.push(Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  30. }
  31. } else {
  32. container.sounds.push(new Sound(parsedSound.name, null, scene));
  33. }
  34. }
  35. }
  36. loadedSounds = [];
  37. });
  38. declare module "../abstractScene" {
  39. export interface AbstractScene {
  40. /**
  41. * The list of sounds used in the scene.
  42. */
  43. sounds: Nullable<Array<Sound>>;
  44. }
  45. }
  46. declare module "../scene" {
  47. export interface Scene {
  48. /**
  49. * @hidden
  50. * Backing field
  51. */
  52. _mainSoundTrack: SoundTrack;
  53. /**
  54. * The main sound track played by the scene.
  55. * It cotains your primary collection of sounds.
  56. */
  57. mainSoundTrack: SoundTrack;
  58. /**
  59. * The list of sound tracks added to the scene
  60. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  61. */
  62. soundTracks: Nullable<Array<SoundTrack>>;
  63. /**
  64. * Gets a sound using a given name
  65. * @param name defines the name to search for
  66. * @return the found sound or null if not found at all.
  67. */
  68. getSoundByName(name: string): Nullable<Sound>;
  69. /**
  70. * Gets or sets if audio support is enabled
  71. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  72. */
  73. audioEnabled: boolean;
  74. /**
  75. * Gets or sets if audio will be output to headphones
  76. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  77. */
  78. headphone: boolean;
  79. }
  80. }
  81. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  82. get: function(this: Scene) {
  83. let compo = this._getComponent(SceneComponentConstants.NAME_AUDIO) as AudioSceneComponent;
  84. if (!compo) {
  85. compo = new AudioSceneComponent(this);
  86. this._addComponent(compo);
  87. }
  88. if (!this._mainSoundTrack) {
  89. this._mainSoundTrack = new SoundTrack(this, { mainTrack: true });
  90. }
  91. return this._mainSoundTrack;
  92. },
  93. enumerable: true,
  94. configurable: true
  95. });
  96. Scene.prototype.getSoundByName = function(name: string): Nullable<Sound> {
  97. var index: number;
  98. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  99. if (this.mainSoundTrack.soundCollection[index].name === name) {
  100. return this.mainSoundTrack.soundCollection[index];
  101. }
  102. }
  103. if (this.soundTracks) {
  104. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  105. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  106. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  107. return this.soundTracks[sdIndex].soundCollection[index];
  108. }
  109. }
  110. }
  111. }
  112. return null;
  113. };
  114. Object.defineProperty(Scene.prototype, "audioEnabled", {
  115. get: function(this: Scene) {
  116. let compo = this._getComponent(SceneComponentConstants.NAME_AUDIO) as AudioSceneComponent;
  117. if (!compo) {
  118. compo = new AudioSceneComponent(this);
  119. this._addComponent(compo);
  120. }
  121. return compo.audioEnabled;
  122. },
  123. set: function(this: Scene, value: boolean) {
  124. let compo = this._getComponent(SceneComponentConstants.NAME_AUDIO) as AudioSceneComponent;
  125. if (!compo) {
  126. compo = new AudioSceneComponent(this);
  127. this._addComponent(compo);
  128. }
  129. if (value) {
  130. compo.enableAudio();
  131. }
  132. else {
  133. compo.disableAudio();
  134. }
  135. },
  136. enumerable: true,
  137. configurable: true
  138. });
  139. Object.defineProperty(Scene.prototype, "headphone", {
  140. get: function(this: Scene) {
  141. let compo = this._getComponent(SceneComponentConstants.NAME_AUDIO) as AudioSceneComponent;
  142. if (!compo) {
  143. compo = new AudioSceneComponent(this);
  144. this._addComponent(compo);
  145. }
  146. return compo.headphone;
  147. },
  148. set: function(this: Scene, value: boolean) {
  149. let compo = this._getComponent(SceneComponentConstants.NAME_AUDIO) as AudioSceneComponent;
  150. if (!compo) {
  151. compo = new AudioSceneComponent(this);
  152. this._addComponent(compo);
  153. }
  154. if (value) {
  155. compo.switchAudioModeForHeadphones();
  156. }
  157. else {
  158. compo.switchAudioModeForNormalSpeakers();
  159. }
  160. },
  161. enumerable: true,
  162. configurable: true
  163. });
  164. /**
  165. * Defines the sound scene component responsible to manage any sounds
  166. * in a given scene.
  167. */
  168. export class AudioSceneComponent implements ISceneSerializableComponent {
  169. /**
  170. * The component name helpfull to identify the component in the list of scene components.
  171. */
  172. public readonly name = SceneComponentConstants.NAME_AUDIO;
  173. /**
  174. * The scene the component belongs to.
  175. */
  176. public scene: Scene;
  177. private _audioEnabled = true;
  178. /**
  179. * Gets whether audio is enabled or not.
  180. * Please use related enable/disable method to switch state.
  181. */
  182. public get audioEnabled(): boolean {
  183. return this._audioEnabled;
  184. }
  185. private _headphone = false;
  186. /**
  187. * Gets whether audio is outputing to headphone or not.
  188. * Please use the according Switch methods to change output.
  189. */
  190. public get headphone(): boolean {
  191. return this._headphone;
  192. }
  193. /**
  194. * Creates a new instance of the component for the given scene
  195. * @param scene Defines the scene to register the component in
  196. */
  197. constructor(scene: Scene) {
  198. this.scene = scene;
  199. scene.soundTracks = new Array<SoundTrack>();
  200. scene.sounds = new Array<Sound>();
  201. }
  202. /**
  203. * Registers the component in a given scene
  204. */
  205. public register(): void {
  206. this.scene._afterRenderStage.registerStep(SceneComponentConstants.STEP_AFTERRENDER_AUDIO, this, this._afterRender);
  207. }
  208. /**
  209. * Rebuilds the elements related to this component in case of
  210. * context lost for instance.
  211. */
  212. public rebuild(): void {
  213. // Nothing to do here. (Not rendering related)
  214. }
  215. /**
  216. * Serializes the component data to the specified json object
  217. * @param serializationObject The object to serialize to
  218. */
  219. public serialize(serializationObject: any): void {
  220. serializationObject.sounds = [];
  221. if (this.scene.soundTracks) {
  222. for (var index = 0; index < this.scene.soundTracks.length; index++) {
  223. var soundtrack = this.scene.soundTracks[index];
  224. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  225. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  226. }
  227. }
  228. }
  229. }
  230. /**
  231. * Adds all the elements from the container to the scene
  232. * @param container the container holding the elements
  233. */
  234. public addFromContainer(container: AbstractScene): void {
  235. if (!container.sounds) {
  236. return;
  237. }
  238. container.sounds.forEach((sound) => {
  239. sound.play();
  240. sound.autoplay = true;
  241. this.scene.mainSoundTrack.AddSound(sound);
  242. });
  243. }
  244. /**
  245. * Removes all the elements in the container from the scene
  246. * @param container contains the elements to remove
  247. * @param dispose if the removed element should be disposed (default: false)
  248. */
  249. public removeFromContainer(container: AbstractScene, dispose = false): void {
  250. if (!container.sounds) {
  251. return;
  252. }
  253. container.sounds.forEach((sound) => {
  254. sound.stop();
  255. sound.autoplay = false;
  256. this.scene.mainSoundTrack.RemoveSound(sound);
  257. if (dispose) {
  258. sound.dispose();
  259. }
  260. });
  261. }
  262. /**
  263. * Disposes the component and the associated ressources.
  264. */
  265. public dispose(): void {
  266. const scene = this.scene;
  267. if (scene._mainSoundTrack) {
  268. scene.mainSoundTrack.dispose();
  269. }
  270. if (scene.soundTracks) {
  271. for (var scIndex = 0; scIndex < scene.soundTracks.length; scIndex++) {
  272. scene.soundTracks[scIndex].dispose();
  273. }
  274. }
  275. }
  276. /**
  277. * Disables audio in the associated scene.
  278. */
  279. public disableAudio() {
  280. const scene = this.scene;
  281. this._audioEnabled = false;
  282. let i: number;
  283. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  284. scene.mainSoundTrack.soundCollection[i].pause();
  285. }
  286. if (scene.soundTracks) {
  287. for (i = 0; i < scene.soundTracks.length; i++) {
  288. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  289. scene.soundTracks[i].soundCollection[j].pause();
  290. }
  291. }
  292. }
  293. }
  294. /**
  295. * Enables audio in the associated scene.
  296. */
  297. public enableAudio() {
  298. const scene = this.scene;
  299. this._audioEnabled = true;
  300. let i: number;
  301. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  302. if (scene.mainSoundTrack.soundCollection[i].isPaused) {
  303. scene.mainSoundTrack.soundCollection[i].play();
  304. }
  305. }
  306. if (scene.soundTracks) {
  307. for (i = 0; i < scene.soundTracks.length; i++) {
  308. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  309. if (scene.soundTracks[i].soundCollection[j].isPaused) {
  310. scene.soundTracks[i].soundCollection[j].play();
  311. }
  312. }
  313. }
  314. }
  315. }
  316. /**
  317. * Switch audio to headphone output.
  318. */
  319. public switchAudioModeForHeadphones() {
  320. const scene = this.scene;
  321. this._headphone = true;
  322. scene.mainSoundTrack.switchPanningModelToHRTF();
  323. if (scene.soundTracks) {
  324. for (var i = 0; i < scene.soundTracks.length; i++) {
  325. scene.soundTracks[i].switchPanningModelToHRTF();
  326. }
  327. }
  328. }
  329. /**
  330. * Switch audio to normal speakers.
  331. */
  332. public switchAudioModeForNormalSpeakers() {
  333. const scene = this.scene;
  334. this._headphone = false;
  335. scene.mainSoundTrack.switchPanningModelToEqualPower();
  336. if (scene.soundTracks) {
  337. for (var i = 0; i < scene.soundTracks.length; i++) {
  338. scene.soundTracks[i].switchPanningModelToEqualPower();
  339. }
  340. }
  341. }
  342. private _afterRender() {
  343. const scene = this.scene;
  344. if (!this._audioEnabled || !scene._mainSoundTrack || !scene.soundTracks || (scene._mainSoundTrack.soundCollection.length === 0 && scene.soundTracks.length === 1)) {
  345. return;
  346. }
  347. var listeningCamera: Nullable<Camera>;
  348. var audioEngine = Engine.audioEngine;
  349. if (scene.activeCameras.length > 0) {
  350. listeningCamera = scene.activeCameras[0];
  351. } else {
  352. listeningCamera = scene.activeCamera;
  353. }
  354. if (listeningCamera && audioEngine.audioContext) {
  355. audioEngine.audioContext.listener.setPosition(listeningCamera.globalPosition.x, listeningCamera.globalPosition.y, listeningCamera.globalPosition.z);
  356. // for VR cameras
  357. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  358. listeningCamera = listeningCamera.rigCameras[0];
  359. }
  360. var mat = Matrix.Invert(listeningCamera.getViewMatrix());
  361. var cameraDirection = Vector3.TransformNormal(new Vector3(0, 0, -1), mat);
  362. cameraDirection.normalize();
  363. // To avoid some errors on GearVR
  364. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  365. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  366. }
  367. var i: number;
  368. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  369. var sound = scene.mainSoundTrack.soundCollection[i];
  370. if (sound.useCustomAttenuation) {
  371. sound.updateDistanceFromListener();
  372. }
  373. }
  374. if (scene.soundTracks) {
  375. for (i = 0; i < scene.soundTracks.length; i++) {
  376. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  377. sound = scene.soundTracks[i].soundCollection[j];
  378. if (sound.useCustomAttenuation) {
  379. sound.updateDistanceFromListener();
  380. }
  381. }
  382. }
  383. }
  384. }
  385. }
  386. }
  387. Sound._SceneComponentInitialization = (scene: Scene) => {
  388. let compo = scene._getComponent(SceneComponentConstants.NAME_AUDIO);
  389. if (!compo) {
  390. compo = new AudioSceneComponent(scene);
  391. scene._addComponent(compo);
  392. }
  393. };