babylon.sound.ts 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710
  1. module BABYLON {
  2. export class Sound {
  3. public name: string;
  4. public autoplay: boolean = false;
  5. public loop: boolean = false;
  6. public useCustomAttenuation: boolean = false;
  7. public soundTrackId: number;
  8. public spatialSound: boolean = false;
  9. public refDistance: number = 1;
  10. public rolloffFactor: number = 1;
  11. public maxDistance: number = 100;
  12. public distanceModel: string = "linear";
  13. private _panningModel: string = "equalpower";
  14. public onended: () => any;
  15. private _playbackRate: number = 1;
  16. private _streaming: boolean = false;
  17. private _startTime: number = 0;
  18. private _startOffset: number = 0;
  19. private _position: Vector3 = Vector3.Zero();
  20. private _localDirection: Vector3 = new Vector3(1, 0, 0);
  21. private _volume: number = 1;
  22. private _isLoaded: boolean = false;
  23. private _isReadyToPlay: boolean = false;
  24. public isPlaying: boolean = false;
  25. public isPaused: boolean = false;
  26. private _isDirectional: boolean = false;
  27. private _readyToPlayCallback: Nullable<() => any>;
  28. private _audioBuffer: Nullable<AudioBuffer>;
  29. private _soundSource: Nullable<AudioBufferSourceNode>;
  30. private _streamingSource: MediaElementAudioSourceNode
  31. private _soundPanner: Nullable<PannerNode>;
  32. private _soundGain: Nullable<GainNode>;
  33. private _inputAudioNode: AudioNode;
  34. private _ouputAudioNode: AudioNode;
  35. // Used if you'd like to create a directional sound.
  36. // If not set, the sound will be omnidirectional
  37. private _coneInnerAngle: number = 360;
  38. private _coneOuterAngle: number = 360;
  39. private _coneOuterGain: number = 0;
  40. private _scene: Scene;
  41. private _connectedMesh: Nullable<AbstractMesh>;
  42. private _customAttenuationFunction: (currentVolume: number, currentDistance: number, maxDistance: number, refDistance: number, rolloffFactor: number) => number;
  43. private _registerFunc: Nullable<(connectedMesh: AbstractMesh) => any>;
  44. private _isOutputConnected = false;
  45. private _htmlAudioElement: HTMLAudioElement;
  46. private _urlType: string = "Unknown";
  47. /**
  48. * Create a sound and attach it to a scene
  49. * @param name Name of your sound
  50. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  51. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  52. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  53. */
  54. constructor(name: string, urlOrArrayBuffer: any, scene: Scene, readyToPlayCallback: Nullable<() => void> = null, options?: any) {
  55. this.name = name;
  56. this._scene = scene;
  57. this._readyToPlayCallback = readyToPlayCallback;
  58. // Default custom attenuation function is a linear attenuation
  59. this._customAttenuationFunction = (currentVolume: number, currentDistance: number, maxDistance: number, refDistance: number, rolloffFactor: number) => {
  60. if (currentDistance < maxDistance) {
  61. return currentVolume * (1 - currentDistance / maxDistance);
  62. }
  63. else {
  64. return 0;
  65. }
  66. };
  67. if (options) {
  68. this.autoplay = options.autoplay || false;
  69. this.loop = options.loop || false;
  70. // if volume === 0, we need another way to check this option
  71. if (options.volume !== undefined) {
  72. this._volume = options.volume;
  73. }
  74. this.spatialSound = options.spatialSound || false;
  75. this.maxDistance = options.maxDistance || 100;
  76. this.useCustomAttenuation = options.useCustomAttenuation || false;
  77. this.rolloffFactor = options.rolloffFactor || 1;
  78. this.refDistance = options.refDistance || 1;
  79. this.distanceModel = options.distanceModel || "linear";
  80. this._playbackRate = options.playbackRate || 1;
  81. this._streaming = options.streaming || false;
  82. }
  83. if (Engine.audioEngine.canUseWebAudio && Engine.audioEngine.audioContext) {
  84. this._soundGain = Engine.audioEngine.audioContext.createGain();
  85. this._soundGain.gain.value = this._volume;
  86. this._inputAudioNode = this._soundGain;
  87. this._ouputAudioNode = this._soundGain;
  88. if (this.spatialSound) {
  89. this._createSpatialParameters();
  90. }
  91. this._scene.mainSoundTrack.AddSound(this);
  92. var validParameter = true;
  93. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  94. if (urlOrArrayBuffer) {
  95. if (typeof (urlOrArrayBuffer) === "string") this._urlType = "String";
  96. if (Array.isArray(urlOrArrayBuffer)) this._urlType = "Array";
  97. if (urlOrArrayBuffer instanceof ArrayBuffer) this._urlType = "ArrayBuffer";
  98. var urls:string[] = [];
  99. var codecSupportedFound = false;
  100. switch (this._urlType) {
  101. case "ArrayBuffer":
  102. if ((<ArrayBuffer>urlOrArrayBuffer).byteLength > 0) {
  103. codecSupportedFound = true;
  104. this._soundLoaded(urlOrArrayBuffer);
  105. }
  106. break;
  107. case "String":
  108. urls.push(urlOrArrayBuffer);
  109. case "Array":
  110. if (urls.length === 0) urls = urlOrArrayBuffer;
  111. // If we found a supported format, we load it immediately and stop the loop
  112. for (var i = 0; i < urls.length; i++) {
  113. var url = urls[i];
  114. if (url.indexOf(".mp3", url.length - 4) !== -1 && Engine.audioEngine.isMP3supported) {
  115. codecSupportedFound = true;
  116. }
  117. if (url.indexOf(".ogg", url.length - 4) !== -1 && Engine.audioEngine.isOGGsupported) {
  118. codecSupportedFound = true;
  119. }
  120. if (url.indexOf(".wav", url.length - 4) !== -1) {
  121. codecSupportedFound = true;
  122. }
  123. if (url.indexOf("blob:") !== -1) {
  124. codecSupportedFound = true;
  125. }
  126. if (codecSupportedFound) {
  127. // Loading sound using XHR2
  128. if (!this._streaming) {
  129. Tools.LoadFile(url, (data) => { this._soundLoaded(data); }, undefined, this._scene.database, true);
  130. }
  131. // Streaming sound using HTML5 Audio tag
  132. else {
  133. this._htmlAudioElement = new Audio(url);
  134. this._htmlAudioElement.controls = false;
  135. this._htmlAudioElement.loop = this.loop;
  136. this._htmlAudioElement.crossOrigin = "anonymous";
  137. this._htmlAudioElement.preload = "auto";
  138. this._htmlAudioElement.addEventListener("canplaythrough", () => {
  139. this._isReadyToPlay = true;
  140. if (this.autoplay) {
  141. this.play();
  142. }
  143. if (this._readyToPlayCallback) {
  144. this._readyToPlayCallback();
  145. }
  146. });
  147. document.body.appendChild(this._htmlAudioElement);
  148. }
  149. break;
  150. }
  151. }
  152. break;
  153. default:
  154. validParameter = false;
  155. break;
  156. }
  157. if (!validParameter) {
  158. Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  159. }
  160. else {
  161. if (!codecSupportedFound) {
  162. this._isReadyToPlay = true;
  163. // Simulating a ready to play event to avoid breaking code path
  164. if (this._readyToPlayCallback) {
  165. window.setTimeout(() => {
  166. if (this._readyToPlayCallback) {
  167. this._readyToPlayCallback();
  168. }
  169. }, 1000);
  170. }
  171. }
  172. }
  173. }
  174. }
  175. else {
  176. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  177. this._scene.mainSoundTrack.AddSound(this);
  178. if (!Engine.audioEngine.WarnedWebAudioUnsupported) {
  179. Tools.Error("Web Audio is not supported by your browser.");
  180. Engine.audioEngine.WarnedWebAudioUnsupported = true;
  181. }
  182. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  183. if (this._readyToPlayCallback) {
  184. window.setTimeout(() => {
  185. if (this._readyToPlayCallback) {
  186. this._readyToPlayCallback();
  187. }
  188. }, 1000);
  189. }
  190. }
  191. }
  192. public dispose() {
  193. if (Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  194. if (this.isPlaying) {
  195. this.stop();
  196. }
  197. this._isReadyToPlay = false;
  198. if (this.soundTrackId === -1) {
  199. this._scene.mainSoundTrack.RemoveSound(this);
  200. }
  201. else {
  202. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  203. }
  204. if (this._soundGain) {
  205. this._soundGain.disconnect();
  206. this._soundGain = null;
  207. }
  208. if (this._soundPanner) {
  209. this._soundPanner.disconnect();
  210. this._soundPanner = null;
  211. }
  212. if (this._soundSource) {
  213. this._soundSource.disconnect();
  214. this._soundSource = null;
  215. }
  216. this._audioBuffer = null;
  217. if (this._htmlAudioElement) {
  218. this._htmlAudioElement.pause();
  219. this._htmlAudioElement.src = "";
  220. document.body.removeChild(this._htmlAudioElement);
  221. }
  222. if (this._connectedMesh && this._registerFunc) {
  223. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  224. this._connectedMesh = null;
  225. }
  226. }
  227. }
  228. public isReady(): boolean {
  229. return this._isReadyToPlay;
  230. }
  231. private _soundLoaded(audioData: ArrayBuffer) {
  232. this._isLoaded = true;
  233. if (!Engine.audioEngine.audioContext) {
  234. return;
  235. }
  236. Engine.audioEngine.audioContext.decodeAudioData(audioData, (buffer) => {
  237. this._audioBuffer = buffer;
  238. this._isReadyToPlay = true;
  239. if (this.autoplay) { this.play(); }
  240. if (this._readyToPlayCallback) { this._readyToPlayCallback(); }
  241. }, (err: any) => { Tools.Error("Error while decoding audio data for: " + this.name + " / Error: " + err); });
  242. }
  243. public setAudioBuffer(audioBuffer: AudioBuffer): void {
  244. if (Engine.audioEngine.canUseWebAudio) {
  245. this._audioBuffer = audioBuffer;
  246. this._isReadyToPlay = true;
  247. }
  248. }
  249. public updateOptions(options: any) {
  250. if (options) {
  251. this.loop = options.loop || this.loop;
  252. this.maxDistance = options.maxDistance || this.maxDistance;
  253. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  254. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  255. this.refDistance = options.refDistance || this.refDistance;
  256. this.distanceModel = options.distanceModel || this.distanceModel;
  257. this._playbackRate = options.playbackRate || this._playbackRate;
  258. this._updateSpatialParameters();
  259. if (this.isPlaying) {
  260. if (this._streaming) {
  261. this._htmlAudioElement.playbackRate = this._playbackRate;
  262. }
  263. else {
  264. if (this._soundSource) {
  265. this._soundSource.playbackRate.value = this._playbackRate;
  266. }
  267. }
  268. }
  269. }
  270. }
  271. private _createSpatialParameters() {
  272. if (Engine.audioEngine.canUseWebAudio && Engine.audioEngine.audioContext) {
  273. if (this._scene.headphone) {
  274. this._panningModel = "HRTF";
  275. }
  276. this._soundPanner = Engine.audioEngine.audioContext.createPanner();
  277. this._updateSpatialParameters();
  278. this._soundPanner.connect(this._ouputAudioNode);
  279. this._inputAudioNode = this._soundPanner;
  280. }
  281. }
  282. private _updateSpatialParameters() {
  283. if (this.spatialSound && this._soundPanner) {
  284. if (this.useCustomAttenuation) {
  285. // Tricks to disable in a way embedded Web Audio attenuation
  286. this._soundPanner.distanceModel = "linear";
  287. this._soundPanner.maxDistance = Number.MAX_VALUE;
  288. this._soundPanner.refDistance = 1;
  289. this._soundPanner.rolloffFactor = 1;
  290. this._soundPanner.panningModel = this._panningModel as any;
  291. }
  292. else {
  293. this._soundPanner.distanceModel = this.distanceModel as any;
  294. this._soundPanner.maxDistance = this.maxDistance;
  295. this._soundPanner.refDistance = this.refDistance;
  296. this._soundPanner.rolloffFactor = this.rolloffFactor;
  297. this._soundPanner.panningModel = this._panningModel as any;
  298. }
  299. }
  300. }
  301. public switchPanningModelToHRTF() {
  302. this._panningModel = "HRTF";
  303. this._switchPanningModel();
  304. }
  305. public switchPanningModelToEqualPower() {
  306. this._panningModel = "equalpower";
  307. this._switchPanningModel();
  308. }
  309. private _switchPanningModel() {
  310. if (Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  311. this._soundPanner.panningModel = this._panningModel as any;
  312. }
  313. }
  314. public connectToSoundTrackAudioNode(soundTrackAudioNode: AudioNode) {
  315. if (Engine.audioEngine.canUseWebAudio) {
  316. if (this._isOutputConnected) {
  317. this._ouputAudioNode.disconnect();
  318. }
  319. this._ouputAudioNode.connect(soundTrackAudioNode);
  320. this._isOutputConnected = true;
  321. }
  322. }
  323. /**
  324. * Transform this sound into a directional source
  325. * @param coneInnerAngle Size of the inner cone in degree
  326. * @param coneOuterAngle Size of the outer cone in degree
  327. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  328. */
  329. public setDirectionalCone(coneInnerAngle: number, coneOuterAngle: number, coneOuterGain: number) {
  330. if (coneOuterAngle < coneInnerAngle) {
  331. Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  332. return;
  333. }
  334. this._coneInnerAngle = coneInnerAngle;
  335. this._coneOuterAngle = coneOuterAngle;
  336. this._coneOuterGain = coneOuterGain;
  337. this._isDirectional = true;
  338. if (this.isPlaying && this.loop) {
  339. this.stop();
  340. this.play();
  341. }
  342. }
  343. public setPosition(newPosition: Vector3) {
  344. this._position = newPosition;
  345. if (Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  346. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  347. }
  348. }
  349. public setLocalDirectionToMesh(newLocalDirection: Vector3) {
  350. this._localDirection = newLocalDirection;
  351. if (Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  352. this._updateDirection();
  353. }
  354. }
  355. private _updateDirection() {
  356. if (!this._connectedMesh || !this._soundPanner) {
  357. return;
  358. }
  359. var mat = this._connectedMesh.getWorldMatrix();
  360. var direction = Vector3.TransformNormal(this._localDirection, mat);
  361. direction.normalize();
  362. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  363. }
  364. public updateDistanceFromListener() {
  365. if (Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  366. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  367. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  368. }
  369. }
  370. public setAttenuationFunction(callback: (currentVolume: number, currentDistance: number, maxDistance: number, refDistance: number, rolloffFactor: number) => number) {
  371. this._customAttenuationFunction = callback;
  372. }
  373. /**
  374. * Play the sound
  375. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  376. * @param offset (optional) Start the sound setting it at a specific time
  377. */
  378. public play(time?: number, offset?: number) {
  379. if (this._isReadyToPlay && this._scene.audioEnabled && Engine.audioEngine.audioContext) {
  380. try {
  381. if (this._startOffset < 0) {
  382. time = -this._startOffset;
  383. this._startOffset = 0;
  384. }
  385. var startTime = time ? Engine.audioEngine.audioContext.currentTime + time : Engine.audioEngine.audioContext.currentTime;
  386. if (!this._soundSource || !this._streamingSource) {
  387. if (this.spatialSound && this._soundPanner) {
  388. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  389. if (this._isDirectional) {
  390. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  391. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  392. this._soundPanner.coneOuterGain = this._coneOuterGain;
  393. if (this._connectedMesh) {
  394. this._updateDirection();
  395. }
  396. else {
  397. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  398. }
  399. }
  400. }
  401. }
  402. if (this._streaming) {
  403. if (!this._streamingSource) {
  404. this._streamingSource = Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  405. this._htmlAudioElement.onended = () => { this._onended(); };
  406. this._htmlAudioElement.playbackRate = this._playbackRate;
  407. }
  408. this._streamingSource.disconnect();
  409. this._streamingSource.connect(this._inputAudioNode);
  410. this._htmlAudioElement.play();
  411. }
  412. else {
  413. this._soundSource = Engine.audioEngine.audioContext.createBufferSource();
  414. this._soundSource.buffer = this._audioBuffer;
  415. this._soundSource.connect(this._inputAudioNode);
  416. this._soundSource.loop = this.loop;
  417. this._soundSource.playbackRate.value = this._playbackRate;
  418. this._soundSource.onended = () => { this._onended(); };
  419. if (this._soundSource.buffer) {
  420. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  421. }
  422. }
  423. this._startTime = startTime;
  424. this.isPlaying = true;
  425. this.isPaused = false;
  426. }
  427. catch (ex) {
  428. Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  429. }
  430. }
  431. }
  432. private _onended() {
  433. this.isPlaying = false;
  434. if (this.onended) {
  435. this.onended();
  436. }
  437. }
  438. /**
  439. * Stop the sound
  440. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  441. */
  442. public stop(time?: number) {
  443. if (this.isPlaying) {
  444. if (this._streaming) {
  445. this._htmlAudioElement.pause();
  446. // Test needed for Firefox or it will generate an Invalid State Error
  447. if (this._htmlAudioElement.currentTime > 0) {
  448. this._htmlAudioElement.currentTime = 0;
  449. }
  450. }
  451. else if (Engine.audioEngine.audioContext && this._soundSource) {
  452. var stopTime = time ? Engine.audioEngine.audioContext.currentTime + time : Engine.audioEngine.audioContext.currentTime;
  453. this._soundSource.stop(stopTime);
  454. this._soundSource.onended = () => {};
  455. if (!this.isPaused) {
  456. this._startOffset = 0;
  457. }
  458. }
  459. this.isPlaying = false;
  460. }
  461. }
  462. public pause() {
  463. if (this.isPlaying) {
  464. this.isPaused = true;
  465. if (this._streaming) {
  466. this._htmlAudioElement.pause();
  467. }
  468. else if (Engine.audioEngine.audioContext) {
  469. this.stop(0);
  470. this._startOffset += Engine.audioEngine.audioContext.currentTime - this._startTime;
  471. }
  472. }
  473. }
  474. public setVolume(newVolume: number, time?: number) {
  475. if (Engine.audioEngine.canUseWebAudio && this._soundGain) {
  476. if (time && Engine.audioEngine.audioContext) {
  477. this._soundGain.gain.cancelScheduledValues(Engine.audioEngine.audioContext.currentTime);
  478. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, Engine.audioEngine.audioContext.currentTime);
  479. this._soundGain.gain.linearRampToValueAtTime(newVolume, Engine.audioEngine.audioContext.currentTime + time);
  480. }
  481. else {
  482. this._soundGain.gain.value = newVolume;
  483. }
  484. }
  485. this._volume = newVolume;
  486. }
  487. public setPlaybackRate(newPlaybackRate: number) {
  488. this._playbackRate = newPlaybackRate;
  489. if (this.isPlaying) {
  490. if (this._streaming) {
  491. this._htmlAudioElement.playbackRate = this._playbackRate;
  492. }
  493. else if (this._soundSource) {
  494. this._soundSource.playbackRate.value = this._playbackRate;
  495. }
  496. }
  497. }
  498. public getVolume(): number {
  499. return this._volume;
  500. }
  501. public attachToMesh(meshToConnectTo: AbstractMesh) {
  502. if (this._connectedMesh && this._registerFunc) {
  503. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  504. this._registerFunc = null;
  505. }
  506. this._connectedMesh = meshToConnectTo;
  507. if (!this.spatialSound) {
  508. this.spatialSound = true;
  509. this._createSpatialParameters();
  510. if (this.isPlaying && this.loop) {
  511. this.stop();
  512. this.play();
  513. }
  514. }
  515. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  516. this._registerFunc = (connectedMesh: AbstractMesh) => this._onRegisterAfterWorldMatrixUpdate(connectedMesh);
  517. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  518. }
  519. public detachFromMesh() {
  520. if (this._connectedMesh && this._registerFunc) {
  521. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  522. this._registerFunc = null;
  523. this._connectedMesh = null;
  524. }
  525. }
  526. private _onRegisterAfterWorldMatrixUpdate(connectedMesh: AbstractMesh): void {
  527. let boundingInfo = connectedMesh.getBoundingInfo();
  528. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  529. if (Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  530. this._updateDirection();
  531. }
  532. }
  533. public clone(): Nullable<Sound> {
  534. if (!this._streaming) {
  535. var setBufferAndRun = () => {
  536. if (this._isReadyToPlay) {
  537. clonedSound._audioBuffer = this.getAudioBuffer();
  538. clonedSound._isReadyToPlay = true;
  539. if (clonedSound.autoplay) { clonedSound.play(); }
  540. }
  541. else {
  542. window.setTimeout(setBufferAndRun, 300);
  543. }
  544. };
  545. var currentOptions = {
  546. autoplay: this.autoplay, loop: this.loop,
  547. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  548. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  549. refDistance: this.refDistance, distanceModel: this.distanceModel
  550. };
  551. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  552. if (this.useCustomAttenuation) {
  553. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  554. }
  555. clonedSound.setPosition(this._position);
  556. clonedSound.setPlaybackRate(this._playbackRate);
  557. setBufferAndRun();
  558. return clonedSound;
  559. }
  560. // Can't clone a streaming sound
  561. else {
  562. return null;
  563. }
  564. }
  565. public getAudioBuffer() {
  566. return this._audioBuffer;
  567. }
  568. public serialize(): any {
  569. var serializationObject: any = {
  570. name: this.name,
  571. url: this.name,
  572. autoplay: this.autoplay,
  573. loop: this.loop,
  574. volume: this._volume,
  575. spatialSound: this.spatialSound,
  576. maxDistance: this.maxDistance,
  577. rolloffFactor: this.rolloffFactor,
  578. refDistance: this.refDistance,
  579. distanceModel: this.distanceModel,
  580. playbackRate: this._playbackRate,
  581. panningModel: this._panningModel,
  582. soundTrackId: this.soundTrackId
  583. };
  584. if (this.spatialSound) {
  585. if (this._connectedMesh)
  586. serializationObject.connectedMeshId = this._connectedMesh.id;
  587. serializationObject.position = this._position.asArray();
  588. serializationObject.refDistance = this.refDistance;
  589. serializationObject.distanceModel = this.distanceModel;
  590. serializationObject.isDirectional = this._isDirectional;
  591. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  592. serializationObject.coneInnerAngle = this._coneInnerAngle;
  593. serializationObject.coneOuterAngle = this._coneOuterAngle;
  594. serializationObject.coneOuterGain = this._coneOuterGain;
  595. }
  596. return serializationObject;
  597. }
  598. public static Parse(parsedSound: any, scene: Scene, rootUrl: string, sourceSound?: Sound): Sound {
  599. var soundName = parsedSound.name;
  600. var soundUrl;
  601. if (parsedSound.url) {
  602. soundUrl = rootUrl + parsedSound.url;
  603. }
  604. else {
  605. soundUrl = rootUrl + soundName;
  606. }
  607. var options = {
  608. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  609. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  610. rolloffFactor: parsedSound.rolloffFactor,
  611. refDistance: parsedSound.refDistance,
  612. distanceModel: parsedSound.distanceModel,
  613. playbackRate: parsedSound.playbackRate
  614. };
  615. var newSound: Sound;
  616. if (!sourceSound) {
  617. newSound = new Sound(soundName, soundUrl, scene, () => { scene._removePendingData(newSound); }, options);
  618. scene._addPendingData(newSound);
  619. }
  620. else {
  621. var setBufferAndRun = () => {
  622. if (sourceSound._isReadyToPlay) {
  623. newSound._audioBuffer = sourceSound.getAudioBuffer();
  624. newSound._isReadyToPlay = true;
  625. if (newSound.autoplay) { newSound.play(); }
  626. }
  627. else {
  628. window.setTimeout(setBufferAndRun, 300);
  629. }
  630. }
  631. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  632. setBufferAndRun();
  633. }
  634. if (parsedSound.position) {
  635. var soundPosition = Vector3.FromArray(parsedSound.position);
  636. newSound.setPosition(soundPosition);
  637. }
  638. if (parsedSound.isDirectional) {
  639. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  640. if (parsedSound.localDirectionToMesh) {
  641. var localDirectionToMesh = Vector3.FromArray(parsedSound.localDirectionToMesh);
  642. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  643. }
  644. }
  645. if (parsedSound.connectedMeshId) {
  646. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  647. if (connectedMesh) {
  648. newSound.attachToMesh(connectedMesh);
  649. }
  650. }
  651. return newSound;
  652. }
  653. }
  654. }