babylon.sound.ts 29 KB

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