audioSceneComponent.ts 15 KB

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