audioSceneComponent.ts 15 KB

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