babylon.sound.ts 33 KB

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