sound.js 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188
  1. import { Tools } from "../Misc/tools.js";
  2. import { Observable } from "../Misc/observable.js";
  3. import { Vector3 } from "../Maths/math.vector.js";
  4. import { Engine } from "../Engines/engine.js";
  5. import { Logger } from "../Misc/logger.js";
  6. import { _WarnImport } from "../Misc/devTools.js";
  7. import { EngineStore } from "../Engines/engineStore.js";
  8. /**
  9. * Defines a sound that can be played in the application.
  10. * The sound can either be an ambient track or a simple sound played in reaction to a user action.
  11. * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic
  12. */
  13. export class Sound {
  14. /**
  15. * Does the sound loop after it finishes playing once.
  16. */
  17. get loop() {
  18. return this._loop;
  19. }
  20. set loop(value) {
  21. if (value === this._loop) {
  22. return;
  23. }
  24. this._loop = value;
  25. this.updateOptions({ loop: value });
  26. }
  27. /**
  28. * Gets the current time for the sound.
  29. */
  30. get currentTime() {
  31. if (this._htmlAudioElement) {
  32. return this._htmlAudioElement.currentTime;
  33. }
  34. if (Engine.audioEngine?.audioContext && (this.isPlaying || this.isPaused)) {
  35. // The `_currentTime` member is only updated when the sound is paused. Add the time since the last start
  36. // to get the actual current time.
  37. const timeSinceLastStart = this.isPaused ? 0 : Engine.audioEngine.audioContext.currentTime - this._startTime;
  38. return this._currentTime + timeSinceLastStart;
  39. }
  40. return 0;
  41. }
  42. /**
  43. * Does this sound enables spatial sound.
  44. * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#creating-a-spatial-3d-sound
  45. */
  46. get spatialSound() {
  47. return this._spatialSound;
  48. }
  49. /**
  50. * Does this sound enables spatial sound.
  51. * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#creating-a-spatial-3d-sound
  52. */
  53. set spatialSound(newValue) {
  54. if (newValue == this._spatialSound) {
  55. return;
  56. }
  57. const wasPlaying = this.isPlaying;
  58. this.pause();
  59. if (newValue) {
  60. this._spatialSound = newValue;
  61. this._updateSpatialParameters();
  62. }
  63. else {
  64. this._disableSpatialSound();
  65. }
  66. if (wasPlaying) {
  67. this.play();
  68. }
  69. }
  70. /**
  71. * Create a sound and attach it to a scene
  72. * @param name Name of your sound
  73. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams and AudioBuffers
  74. * @param scene defines the scene the sound belongs to
  75. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  76. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  77. */
  78. constructor(name, urlOrArrayBuffer, scene, readyToPlayCallback = null, options) {
  79. /**
  80. * Does the sound autoplay once loaded.
  81. */
  82. this.autoplay = false;
  83. this._loop = false;
  84. /**
  85. * Does the sound use a custom attenuation curve to simulate the falloff
  86. * happening when the source gets further away from the camera.
  87. * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#creating-your-own-custom-attenuation-function
  88. */
  89. this.useCustomAttenuation = false;
  90. /**
  91. * Is this sound currently played.
  92. */
  93. this.isPlaying = false;
  94. /**
  95. * Is this sound currently paused.
  96. */
  97. this.isPaused = false;
  98. /**
  99. * Define the reference distance the sound should be heard perfectly.
  100. * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#creating-a-spatial-3d-sound
  101. */
  102. this.refDistance = 1;
  103. /**
  104. * Define the roll off factor of spatial sounds.
  105. * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#creating-a-spatial-3d-sound
  106. */
  107. this.rolloffFactor = 1;
  108. /**
  109. * Define the max distance the sound should be heard (intensity just became 0 at this point).
  110. * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#creating-a-spatial-3d-sound
  111. */
  112. this.maxDistance = 100;
  113. /**
  114. * Define the distance attenuation model the sound will follow.
  115. * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#creating-a-spatial-3d-sound
  116. */
  117. this.distanceModel = "linear";
  118. /**
  119. * Gets or sets an object used to store user defined information for the sound.
  120. */
  121. this.metadata = null;
  122. /**
  123. * Observable event when the current playing sound finishes.
  124. */
  125. this.onEndedObservable = new Observable();
  126. this._spatialSound = false;
  127. this._panningModel = "equalpower";
  128. this._playbackRate = 1;
  129. this._streaming = false;
  130. this._startTime = 0;
  131. this._currentTime = 0;
  132. this._position = Vector3.Zero();
  133. this._localDirection = new Vector3(1, 0, 0);
  134. this._volume = 1;
  135. this._isReadyToPlay = false;
  136. this._isDirectional = false;
  137. // Used if you'd like to create a directional sound.
  138. // If not set, the sound will be omnidirectional
  139. this._coneInnerAngle = 360;
  140. this._coneOuterAngle = 360;
  141. this._coneOuterGain = 0;
  142. this._isOutputConnected = false;
  143. this._urlType = "Unknown";
  144. this.name = name;
  145. scene = scene || EngineStore.LastCreatedScene;
  146. if (!scene) {
  147. return;
  148. }
  149. this._scene = scene;
  150. Sound._SceneComponentInitialization(scene);
  151. this._readyToPlayCallback = readyToPlayCallback;
  152. // Default custom attenuation function is a linear attenuation
  153. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  154. this._customAttenuationFunction = (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) => {
  155. if (currentDistance < maxDistance) {
  156. return currentVolume * (1 - currentDistance / maxDistance);
  157. }
  158. else {
  159. return 0;
  160. }
  161. };
  162. if (options) {
  163. this.autoplay = options.autoplay || false;
  164. this._loop = options.loop || false;
  165. // if volume === 0, we need another way to check this option
  166. if (options.volume !== undefined) {
  167. this._volume = options.volume;
  168. }
  169. this._spatialSound = options.spatialSound ?? false;
  170. this.maxDistance = options.maxDistance ?? 100;
  171. this.useCustomAttenuation = options.useCustomAttenuation ?? false;
  172. this.rolloffFactor = options.rolloffFactor || 1;
  173. this.refDistance = options.refDistance || 1;
  174. this.distanceModel = options.distanceModel || "linear";
  175. this._playbackRate = options.playbackRate || 1;
  176. this._streaming = options.streaming ?? false;
  177. this._length = options.length;
  178. this._offset = options.offset;
  179. }
  180. if (Engine.audioEngine?.canUseWebAudio && Engine.audioEngine.audioContext) {
  181. this._soundGain = Engine.audioEngine.audioContext.createGain();
  182. this._soundGain.gain.value = this._volume;
  183. this._inputAudioNode = this._soundGain;
  184. this._outputAudioNode = this._soundGain;
  185. if (this._spatialSound) {
  186. this._createSpatialParameters();
  187. }
  188. this._scene.mainSoundTrack.addSound(this);
  189. let validParameter = true;
  190. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  191. if (urlOrArrayBuffer) {
  192. try {
  193. if (typeof urlOrArrayBuffer === "string") {
  194. this._urlType = "String";
  195. this._url = urlOrArrayBuffer;
  196. }
  197. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  198. this._urlType = "ArrayBuffer";
  199. }
  200. else if (urlOrArrayBuffer instanceof HTMLMediaElement) {
  201. this._urlType = "MediaElement";
  202. }
  203. else if (urlOrArrayBuffer instanceof MediaStream) {
  204. this._urlType = "MediaStream";
  205. }
  206. else if (urlOrArrayBuffer instanceof AudioBuffer) {
  207. this._urlType = "AudioBuffer";
  208. }
  209. else if (Array.isArray(urlOrArrayBuffer)) {
  210. this._urlType = "Array";
  211. }
  212. let urls = [];
  213. let codecSupportedFound = false;
  214. switch (this._urlType) {
  215. case "MediaElement":
  216. this._streaming = true;
  217. this._isReadyToPlay = true;
  218. this._streamingSource = Engine.audioEngine.audioContext.createMediaElementSource(urlOrArrayBuffer);
  219. if (this.autoplay) {
  220. this.play(0, this._offset, this._length);
  221. }
  222. if (this._readyToPlayCallback) {
  223. this._readyToPlayCallback();
  224. }
  225. break;
  226. case "MediaStream":
  227. this._streaming = true;
  228. this._isReadyToPlay = true;
  229. this._streamingSource = Engine.audioEngine.audioContext.createMediaStreamSource(urlOrArrayBuffer);
  230. if (this.autoplay) {
  231. this.play(0, this._offset, this._length);
  232. }
  233. if (this._readyToPlayCallback) {
  234. this._readyToPlayCallback();
  235. }
  236. break;
  237. case "ArrayBuffer":
  238. if (urlOrArrayBuffer.byteLength > 0) {
  239. codecSupportedFound = true;
  240. this._soundLoaded(urlOrArrayBuffer);
  241. }
  242. break;
  243. case "AudioBuffer":
  244. this._audioBufferLoaded(urlOrArrayBuffer);
  245. break;
  246. case "String":
  247. urls.push(urlOrArrayBuffer);
  248. // eslint-disable-next-line no-fallthrough
  249. case "Array":
  250. if (urls.length === 0) {
  251. urls = urlOrArrayBuffer;
  252. }
  253. // If we found a supported format, we load it immediately and stop the loop
  254. for (let i = 0; i < urls.length; i++) {
  255. const url = urls[i];
  256. codecSupportedFound =
  257. (options && options.skipCodecCheck) ||
  258. (url.indexOf(".mp3", url.length - 4) !== -1 && Engine.audioEngine.isMP3supported) ||
  259. (url.indexOf(".ogg", url.length - 4) !== -1 && Engine.audioEngine.isOGGsupported) ||
  260. url.indexOf(".wav", url.length - 4) !== -1 ||
  261. url.indexOf(".m4a", url.length - 4) !== -1 ||
  262. url.indexOf(".mp4", url.length - 4) !== -1 ||
  263. url.indexOf("blob:") !== -1;
  264. if (codecSupportedFound) {
  265. // Loading sound
  266. if (!this._streaming) {
  267. this._scene._loadFile(url, (data) => {
  268. this._soundLoaded(data);
  269. }, undefined, true, true, (exception) => {
  270. if (exception) {
  271. Logger.Error("XHR " + exception.status + " error on: " + url + ".");
  272. }
  273. Logger.Error("Sound creation aborted.");
  274. this._scene.mainSoundTrack.removeSound(this);
  275. });
  276. }
  277. // Streaming sound using HTML5 Audio tag
  278. else {
  279. this._htmlAudioElement = new Audio(url);
  280. this._htmlAudioElement.controls = false;
  281. this._htmlAudioElement.loop = this.loop;
  282. Tools.SetCorsBehavior(url, this._htmlAudioElement);
  283. this._htmlAudioElement.preload = "auto";
  284. this._htmlAudioElement.addEventListener("canplaythrough", () => {
  285. this._isReadyToPlay = true;
  286. if (this.autoplay) {
  287. this.play(0, this._offset, this._length);
  288. }
  289. if (this._readyToPlayCallback) {
  290. this._readyToPlayCallback();
  291. }
  292. });
  293. document.body.appendChild(this._htmlAudioElement);
  294. this._htmlAudioElement.load();
  295. }
  296. break;
  297. }
  298. }
  299. break;
  300. default:
  301. validParameter = false;
  302. break;
  303. }
  304. if (!validParameter) {
  305. Logger.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  306. }
  307. else {
  308. if (!codecSupportedFound) {
  309. this._isReadyToPlay = true;
  310. // Simulating a ready to play event to avoid breaking code path
  311. if (this._readyToPlayCallback) {
  312. setTimeout(() => {
  313. if (this._readyToPlayCallback) {
  314. this._readyToPlayCallback();
  315. }
  316. }, 1000);
  317. }
  318. }
  319. }
  320. }
  321. catch (ex) {
  322. Logger.Error("Unexpected error. Sound creation aborted.");
  323. this._scene.mainSoundTrack.removeSound(this);
  324. }
  325. }
  326. }
  327. else {
  328. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  329. this._scene.mainSoundTrack.addSound(this);
  330. if (Engine.audioEngine && !Engine.audioEngine.WarnedWebAudioUnsupported) {
  331. Logger.Error("Web Audio is not supported by your browser.");
  332. Engine.audioEngine.WarnedWebAudioUnsupported = true;
  333. }
  334. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  335. if (this._readyToPlayCallback) {
  336. setTimeout(() => {
  337. if (this._readyToPlayCallback) {
  338. this._readyToPlayCallback();
  339. }
  340. }, 1000);
  341. }
  342. }
  343. }
  344. /**
  345. * Release the sound and its associated resources
  346. */
  347. dispose() {
  348. if (Engine.audioEngine?.canUseWebAudio) {
  349. if (this.isPlaying) {
  350. this.stop();
  351. }
  352. this._isReadyToPlay = false;
  353. if (this.soundTrackId === -1) {
  354. this._scene.mainSoundTrack.removeSound(this);
  355. }
  356. else if (this._scene.soundTracks) {
  357. this._scene.soundTracks[this.soundTrackId].removeSound(this);
  358. }
  359. if (this._soundGain) {
  360. this._soundGain.disconnect();
  361. this._soundGain = null;
  362. }
  363. if (this._soundPanner) {
  364. this._soundPanner.disconnect();
  365. this._soundPanner = null;
  366. }
  367. if (this._soundSource) {
  368. this._soundSource.disconnect();
  369. this._soundSource = null;
  370. }
  371. this._audioBuffer = null;
  372. if (this._htmlAudioElement) {
  373. this._htmlAudioElement.pause();
  374. this._htmlAudioElement.src = "";
  375. document.body.removeChild(this._htmlAudioElement);
  376. }
  377. if (this._streamingSource) {
  378. this._streamingSource.disconnect();
  379. }
  380. if (this._connectedTransformNode && this._registerFunc) {
  381. this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  382. this._connectedTransformNode = null;
  383. }
  384. this._clearTimeoutsAndObservers();
  385. }
  386. }
  387. /**
  388. * Gets if the sounds is ready to be played or not.
  389. * @returns true if ready, otherwise false
  390. */
  391. isReady() {
  392. return this._isReadyToPlay;
  393. }
  394. /**
  395. * Get the current class name.
  396. * @returns current class name
  397. */
  398. getClassName() {
  399. return "Sound";
  400. }
  401. _audioBufferLoaded(buffer) {
  402. if (!Engine.audioEngine?.audioContext) {
  403. return;
  404. }
  405. this._audioBuffer = buffer;
  406. this._isReadyToPlay = true;
  407. if (this.autoplay) {
  408. this.play(0, this._offset, this._length);
  409. }
  410. if (this._readyToPlayCallback) {
  411. this._readyToPlayCallback();
  412. }
  413. }
  414. _soundLoaded(audioData) {
  415. if (!Engine.audioEngine?.audioContext) {
  416. return;
  417. }
  418. Engine.audioEngine.audioContext.decodeAudioData(audioData, (buffer) => {
  419. this._audioBufferLoaded(buffer);
  420. }, (err) => {
  421. Logger.Error("Error while decoding audio data for: " + this.name + " / Error: " + err);
  422. });
  423. }
  424. /**
  425. * Sets the data of the sound from an audiobuffer
  426. * @param audioBuffer The audioBuffer containing the data
  427. */
  428. setAudioBuffer(audioBuffer) {
  429. if (Engine.audioEngine?.canUseWebAudio) {
  430. this._audioBuffer = audioBuffer;
  431. this._isReadyToPlay = true;
  432. }
  433. }
  434. /**
  435. * Updates the current sounds options such as maxdistance, loop...
  436. * @param options A JSON object containing values named as the object properties
  437. */
  438. updateOptions(options) {
  439. if (options) {
  440. this.loop = options.loop ?? this.loop;
  441. this.maxDistance = options.maxDistance ?? this.maxDistance;
  442. this.useCustomAttenuation = options.useCustomAttenuation ?? this.useCustomAttenuation;
  443. this.rolloffFactor = options.rolloffFactor ?? this.rolloffFactor;
  444. this.refDistance = options.refDistance ?? this.refDistance;
  445. this.distanceModel = options.distanceModel ?? this.distanceModel;
  446. this._playbackRate = options.playbackRate ?? this._playbackRate;
  447. this._length = options.length ?? undefined;
  448. this.spatialSound = options.spatialSound ?? this._spatialSound;
  449. this._setOffset(options.offset ?? undefined);
  450. this.setVolume(options.volume ?? this._volume);
  451. this._updateSpatialParameters();
  452. if (this.isPlaying) {
  453. if (this._streaming && this._htmlAudioElement) {
  454. this._htmlAudioElement.playbackRate = this._playbackRate;
  455. if (this._htmlAudioElement.loop !== this.loop) {
  456. this._htmlAudioElement.loop = this.loop;
  457. }
  458. }
  459. else {
  460. if (this._soundSource) {
  461. this._soundSource.playbackRate.value = this._playbackRate;
  462. if (this._soundSource.loop !== this.loop) {
  463. this._soundSource.loop = this.loop;
  464. }
  465. if (this._offset !== undefined && this._soundSource.loopStart !== this._offset) {
  466. this._soundSource.loopStart = this._offset;
  467. }
  468. if (this._length !== undefined && this._length !== this._soundSource.loopEnd) {
  469. this._soundSource.loopEnd = (this._offset | 0) + this._length;
  470. }
  471. }
  472. }
  473. }
  474. }
  475. }
  476. _createSpatialParameters() {
  477. if (Engine.audioEngine?.canUseWebAudio && Engine.audioEngine.audioContext) {
  478. if (this._scene.headphone) {
  479. this._panningModel = "HRTF";
  480. }
  481. this._soundPanner = this._soundPanner ?? Engine.audioEngine.audioContext.createPanner();
  482. if (this._soundPanner && this._outputAudioNode) {
  483. this._updateSpatialParameters();
  484. this._soundPanner.connect(this._outputAudioNode);
  485. this._inputAudioNode = this._soundPanner;
  486. }
  487. }
  488. }
  489. _disableSpatialSound() {
  490. if (!this._spatialSound) {
  491. return;
  492. }
  493. this._inputAudioNode = this._soundGain;
  494. this._soundPanner?.disconnect();
  495. this._soundPanner = null;
  496. this._spatialSound = false;
  497. }
  498. _updateSpatialParameters() {
  499. if (!this._spatialSound) {
  500. return;
  501. }
  502. if (this._soundPanner) {
  503. if (this.useCustomAttenuation) {
  504. // Tricks to disable in a way embedded Web Audio attenuation
  505. this._soundPanner.distanceModel = "linear";
  506. this._soundPanner.maxDistance = Number.MAX_VALUE;
  507. this._soundPanner.refDistance = 1;
  508. this._soundPanner.rolloffFactor = 1;
  509. this._soundPanner.panningModel = this._panningModel;
  510. }
  511. else {
  512. this._soundPanner.distanceModel = this.distanceModel;
  513. this._soundPanner.maxDistance = this.maxDistance;
  514. this._soundPanner.refDistance = this.refDistance;
  515. this._soundPanner.rolloffFactor = this.rolloffFactor;
  516. this._soundPanner.panningModel = this._panningModel;
  517. }
  518. }
  519. else {
  520. this._createSpatialParameters();
  521. }
  522. }
  523. /**
  524. * Switch the panning model to HRTF:
  525. * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects.
  526. * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#creating-a-spatial-3d-sound
  527. */
  528. switchPanningModelToHRTF() {
  529. this._panningModel = "HRTF";
  530. this._switchPanningModel();
  531. }
  532. /**
  533. * Switch the panning model to Equal Power:
  534. * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value.
  535. * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#creating-a-spatial-3d-sound
  536. */
  537. switchPanningModelToEqualPower() {
  538. this._panningModel = "equalpower";
  539. this._switchPanningModel();
  540. }
  541. _switchPanningModel() {
  542. if (Engine.audioEngine?.canUseWebAudio && this._spatialSound && this._soundPanner) {
  543. this._soundPanner.panningModel = this._panningModel;
  544. }
  545. }
  546. /**
  547. * Connect this sound to a sound track audio node like gain...
  548. * @param soundTrackAudioNode the sound track audio node to connect to
  549. */
  550. connectToSoundTrackAudioNode(soundTrackAudioNode) {
  551. if (Engine.audioEngine?.canUseWebAudio && this._outputAudioNode) {
  552. if (this._isOutputConnected) {
  553. this._outputAudioNode.disconnect();
  554. }
  555. this._outputAudioNode.connect(soundTrackAudioNode);
  556. this._isOutputConnected = true;
  557. }
  558. }
  559. /**
  560. * Transform this sound into a directional source
  561. * @param coneInnerAngle Size of the inner cone in degree
  562. * @param coneOuterAngle Size of the outer cone in degree
  563. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  564. */
  565. setDirectionalCone(coneInnerAngle, coneOuterAngle, coneOuterGain) {
  566. if (coneOuterAngle < coneInnerAngle) {
  567. Logger.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  568. return;
  569. }
  570. this._coneInnerAngle = coneInnerAngle;
  571. this._coneOuterAngle = coneOuterAngle;
  572. this._coneOuterGain = coneOuterGain;
  573. this._isDirectional = true;
  574. if (this.isPlaying && this.loop) {
  575. this.stop();
  576. this.play(0, this._offset, this._length);
  577. }
  578. }
  579. /**
  580. * Gets or sets the inner angle for the directional cone.
  581. */
  582. get directionalConeInnerAngle() {
  583. return this._coneInnerAngle;
  584. }
  585. /**
  586. * Gets or sets the inner angle for the directional cone.
  587. */
  588. set directionalConeInnerAngle(value) {
  589. if (value != this._coneInnerAngle) {
  590. if (this._coneOuterAngle < value) {
  591. Logger.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  592. return;
  593. }
  594. this._coneInnerAngle = value;
  595. if (Engine.audioEngine?.canUseWebAudio && this._spatialSound && this._soundPanner) {
  596. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  597. }
  598. }
  599. }
  600. /**
  601. * Gets or sets the outer angle for the directional cone.
  602. */
  603. get directionalConeOuterAngle() {
  604. return this._coneOuterAngle;
  605. }
  606. /**
  607. * Gets or sets the outer angle for the directional cone.
  608. */
  609. set directionalConeOuterAngle(value) {
  610. if (value != this._coneOuterAngle) {
  611. if (value < this._coneInnerAngle) {
  612. Logger.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  613. return;
  614. }
  615. this._coneOuterAngle = value;
  616. if (Engine.audioEngine?.canUseWebAudio && this._spatialSound && this._soundPanner) {
  617. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  618. }
  619. }
  620. }
  621. /**
  622. * Sets the position of the emitter if spatial sound is enabled
  623. * @param newPosition Defines the new position
  624. */
  625. setPosition(newPosition) {
  626. if (newPosition.equals(this._position)) {
  627. return;
  628. }
  629. this._position.copyFrom(newPosition);
  630. if (Engine.audioEngine?.canUseWebAudio && this._spatialSound && this._soundPanner && !isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  631. this._soundPanner.positionX.value = this._position.x;
  632. this._soundPanner.positionY.value = this._position.y;
  633. this._soundPanner.positionZ.value = this._position.z;
  634. }
  635. }
  636. /**
  637. * Sets the local direction of the emitter if spatial sound is enabled
  638. * @param newLocalDirection Defines the new local direction
  639. */
  640. setLocalDirectionToMesh(newLocalDirection) {
  641. this._localDirection = newLocalDirection;
  642. if (Engine.audioEngine?.canUseWebAudio && this._connectedTransformNode && this.isPlaying) {
  643. this._updateDirection();
  644. }
  645. }
  646. _updateDirection() {
  647. if (!this._connectedTransformNode || !this._soundPanner) {
  648. return;
  649. }
  650. const mat = this._connectedTransformNode.getWorldMatrix();
  651. const direction = Vector3.TransformNormal(this._localDirection, mat);
  652. direction.normalize();
  653. this._soundPanner.orientationX.value = direction.x;
  654. this._soundPanner.orientationY.value = direction.y;
  655. this._soundPanner.orientationZ.value = direction.z;
  656. }
  657. /** @internal */
  658. updateDistanceFromListener() {
  659. if (Engine.audioEngine?.canUseWebAudio && this._connectedTransformNode && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  660. const distance = this._scene.audioListenerPositionProvider
  661. ? this._connectedTransformNode.position.subtract(this._scene.audioListenerPositionProvider()).length()
  662. : this._connectedTransformNode.getDistanceToCamera(this._scene.activeCamera);
  663. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  664. }
  665. }
  666. /**
  667. * Sets a new custom attenuation function for the sound.
  668. * @param callback Defines the function used for the attenuation
  669. * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#creating-your-own-custom-attenuation-function
  670. */
  671. setAttenuationFunction(callback) {
  672. this._customAttenuationFunction = callback;
  673. }
  674. /**
  675. * Play the sound
  676. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  677. * @param offset (optional) Start the sound at a specific time in seconds
  678. * @param length (optional) Sound duration (in seconds)
  679. */
  680. play(time, offset, length) {
  681. if (this._isReadyToPlay && this._scene.audioEnabled && Engine.audioEngine?.audioContext) {
  682. try {
  683. this._clearTimeoutsAndObservers();
  684. let startTime = time ? Engine.audioEngine?.audioContext.currentTime + time : Engine.audioEngine?.audioContext.currentTime;
  685. if (!this._soundSource || !this._streamingSource) {
  686. if (this._spatialSound && this._soundPanner) {
  687. if (!isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  688. this._soundPanner.positionX.value = this._position.x;
  689. this._soundPanner.positionY.value = this._position.y;
  690. this._soundPanner.positionZ.value = this._position.z;
  691. }
  692. if (this._isDirectional) {
  693. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  694. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  695. this._soundPanner.coneOuterGain = this._coneOuterGain;
  696. if (this._connectedTransformNode) {
  697. this._updateDirection();
  698. }
  699. else {
  700. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  701. }
  702. }
  703. }
  704. }
  705. if (this._streaming) {
  706. if (!this._streamingSource) {
  707. this._streamingSource = Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  708. this._htmlAudioElement.onended = () => {
  709. this._onended();
  710. };
  711. this._htmlAudioElement.playbackRate = this._playbackRate;
  712. }
  713. this._streamingSource.disconnect();
  714. if (this._inputAudioNode) {
  715. this._streamingSource.connect(this._inputAudioNode);
  716. }
  717. if (this._htmlAudioElement) {
  718. // required to manage properly the new suspended default state of Chrome
  719. // When the option 'streaming: true' is used, we need first to wait for
  720. // the audio engine to be unlocked by a user gesture before trying to play
  721. // an HTML Audio element
  722. const tryToPlay = () => {
  723. if (Engine.audioEngine?.unlocked) {
  724. const playPromise = this._htmlAudioElement.play();
  725. // In browsers that don’t yet support this functionality,
  726. // playPromise won’t be defined.
  727. if (playPromise !== undefined) {
  728. playPromise.catch(() => {
  729. // Automatic playback failed.
  730. // Waiting for the audio engine to be unlocked by user click on unmute
  731. Engine.audioEngine?.lock();
  732. if (this.loop || this.autoplay) {
  733. this._audioUnlockedObserver = Engine.audioEngine?.onAudioUnlockedObservable.addOnce(() => {
  734. tryToPlay();
  735. });
  736. }
  737. });
  738. }
  739. }
  740. else {
  741. if (this.loop || this.autoplay) {
  742. this._audioUnlockedObserver = Engine.audioEngine?.onAudioUnlockedObservable.addOnce(() => {
  743. tryToPlay();
  744. });
  745. }
  746. }
  747. };
  748. tryToPlay();
  749. }
  750. }
  751. else {
  752. const tryToPlay = () => {
  753. if (Engine.audioEngine?.audioContext) {
  754. length = length || this._length;
  755. if (offset !== undefined) {
  756. this._setOffset(offset);
  757. }
  758. if (this._soundSource) {
  759. const oldSource = this._soundSource;
  760. oldSource.onended = () => {
  761. oldSource.disconnect();
  762. };
  763. }
  764. this._soundSource = Engine.audioEngine?.audioContext.createBufferSource();
  765. if (this._soundSource && this._inputAudioNode) {
  766. this._soundSource.buffer = this._audioBuffer;
  767. this._soundSource.connect(this._inputAudioNode);
  768. this._soundSource.loop = this.loop;
  769. if (offset !== undefined) {
  770. this._soundSource.loopStart = offset;
  771. }
  772. if (length !== undefined) {
  773. this._soundSource.loopEnd = (offset | 0) + length;
  774. }
  775. this._soundSource.playbackRate.value = this._playbackRate;
  776. this._soundSource.onended = () => {
  777. this._onended();
  778. };
  779. startTime = time ? Engine.audioEngine?.audioContext.currentTime + time : Engine.audioEngine.audioContext.currentTime;
  780. const actualOffset = ((this.isPaused ? this.currentTime : 0) + (this._offset ?? 0)) % this._soundSource.buffer.duration;
  781. this._soundSource.start(startTime, actualOffset, this.loop ? undefined : length);
  782. }
  783. }
  784. };
  785. if (Engine.audioEngine?.audioContext.state === "suspended") {
  786. // Wait a bit for FF as context seems late to be ready.
  787. this._tryToPlayTimeout = setTimeout(() => {
  788. if (Engine.audioEngine?.audioContext.state === "suspended") {
  789. // Automatic playback failed.
  790. // Waiting for the audio engine to be unlocked by user click on unmute
  791. Engine.audioEngine.lock();
  792. if (this.loop || this.autoplay) {
  793. this._audioUnlockedObserver = Engine.audioEngine.onAudioUnlockedObservable.addOnce(() => {
  794. tryToPlay();
  795. });
  796. }
  797. }
  798. else {
  799. tryToPlay();
  800. }
  801. }, 500);
  802. }
  803. else {
  804. tryToPlay();
  805. }
  806. }
  807. this._startTime = startTime;
  808. this.isPlaying = true;
  809. this.isPaused = false;
  810. }
  811. catch (ex) {
  812. Logger.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  813. }
  814. }
  815. }
  816. _onended() {
  817. this.isPlaying = false;
  818. this._startTime = 0;
  819. this._currentTime = 0;
  820. if (this.onended) {
  821. this.onended();
  822. }
  823. this.onEndedObservable.notifyObservers(this);
  824. }
  825. /**
  826. * Stop the sound
  827. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  828. */
  829. stop(time) {
  830. if (this.isPlaying) {
  831. this._clearTimeoutsAndObservers();
  832. if (this._streaming) {
  833. if (this._htmlAudioElement) {
  834. this._htmlAudioElement.pause();
  835. // Test needed for Firefox or it will generate an Invalid State Error
  836. if (this._htmlAudioElement.currentTime > 0) {
  837. this._htmlAudioElement.currentTime = 0;
  838. }
  839. }
  840. else {
  841. this._streamingSource.disconnect();
  842. }
  843. this.isPlaying = false;
  844. }
  845. else if (Engine.audioEngine?.audioContext && this._soundSource) {
  846. const stopTime = time ? Engine.audioEngine.audioContext.currentTime + time : undefined;
  847. this._soundSource.onended = () => {
  848. this.isPlaying = false;
  849. this.isPaused = false;
  850. this._startTime = 0;
  851. this._currentTime = 0;
  852. if (this._soundSource) {
  853. this._soundSource.onended = () => void 0;
  854. }
  855. this._onended();
  856. };
  857. this._soundSource.stop(stopTime);
  858. }
  859. else {
  860. this.isPlaying = false;
  861. }
  862. }
  863. else if (this.isPaused) {
  864. this.isPaused = false;
  865. this._startTime = 0;
  866. this._currentTime = 0;
  867. }
  868. }
  869. /**
  870. * Put the sound in pause
  871. */
  872. pause() {
  873. if (this.isPlaying) {
  874. this._clearTimeoutsAndObservers();
  875. if (this._streaming) {
  876. if (this._htmlAudioElement) {
  877. this._htmlAudioElement.pause();
  878. }
  879. else {
  880. this._streamingSource.disconnect();
  881. }
  882. this.isPlaying = false;
  883. this.isPaused = true;
  884. }
  885. else if (Engine.audioEngine?.audioContext && this._soundSource) {
  886. this._soundSource.onended = () => void 0;
  887. this._soundSource.stop();
  888. this.isPlaying = false;
  889. this.isPaused = true;
  890. this._currentTime += Engine.audioEngine.audioContext.currentTime - this._startTime;
  891. }
  892. }
  893. }
  894. /**
  895. * Sets a dedicated volume for this sounds
  896. * @param newVolume Define the new volume of the sound
  897. * @param time Define time for gradual change to new volume
  898. */
  899. setVolume(newVolume, time) {
  900. if (Engine.audioEngine?.canUseWebAudio && this._soundGain) {
  901. if (time && Engine.audioEngine.audioContext) {
  902. this._soundGain.gain.cancelScheduledValues(Engine.audioEngine.audioContext.currentTime);
  903. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, Engine.audioEngine.audioContext.currentTime);
  904. this._soundGain.gain.linearRampToValueAtTime(newVolume, Engine.audioEngine.audioContext.currentTime + time);
  905. }
  906. else {
  907. this._soundGain.gain.value = newVolume;
  908. }
  909. }
  910. this._volume = newVolume;
  911. }
  912. /**
  913. * Set the sound play back rate
  914. * @param newPlaybackRate Define the playback rate the sound should be played at
  915. */
  916. setPlaybackRate(newPlaybackRate) {
  917. this._playbackRate = newPlaybackRate;
  918. if (this.isPlaying) {
  919. if (this._streaming && this._htmlAudioElement) {
  920. this._htmlAudioElement.playbackRate = this._playbackRate;
  921. }
  922. else if (this._soundSource) {
  923. this._soundSource.playbackRate.value = this._playbackRate;
  924. }
  925. }
  926. }
  927. /**
  928. * Gets the sound play back rate.
  929. * @returns the play back rate of the sound
  930. */
  931. getPlaybackRate() {
  932. return this._playbackRate;
  933. }
  934. /**
  935. * Gets the volume of the sound.
  936. * @returns the volume of the sound
  937. */
  938. getVolume() {
  939. return this._volume;
  940. }
  941. /**
  942. * Attach the sound to a dedicated mesh
  943. * @param transformNode The transform node to connect the sound with
  944. * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#attaching-a-sound-to-a-mesh
  945. */
  946. attachToMesh(transformNode) {
  947. if (this._connectedTransformNode && this._registerFunc) {
  948. this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  949. this._registerFunc = null;
  950. }
  951. this._connectedTransformNode = transformNode;
  952. if (!this._spatialSound) {
  953. this._spatialSound = true;
  954. this._createSpatialParameters();
  955. if (this.isPlaying && this.loop) {
  956. this.stop();
  957. this.play(0, this._offset, this._length);
  958. }
  959. }
  960. this._onRegisterAfterWorldMatrixUpdate(this._connectedTransformNode);
  961. this._registerFunc = (transformNode) => this._onRegisterAfterWorldMatrixUpdate(transformNode);
  962. this._connectedTransformNode.registerAfterWorldMatrixUpdate(this._registerFunc);
  963. }
  964. /**
  965. * Detach the sound from the previously attached mesh
  966. * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#attaching-a-sound-to-a-mesh
  967. */
  968. detachFromMesh() {
  969. if (this._connectedTransformNode && this._registerFunc) {
  970. this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  971. this._registerFunc = null;
  972. this._connectedTransformNode = null;
  973. }
  974. }
  975. _onRegisterAfterWorldMatrixUpdate(node) {
  976. if (!node.getBoundingInfo) {
  977. this.setPosition(node.absolutePosition);
  978. }
  979. else {
  980. const mesh = node;
  981. const boundingInfo = mesh.getBoundingInfo();
  982. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  983. }
  984. if (Engine.audioEngine?.canUseWebAudio && this._isDirectional && this.isPlaying) {
  985. this._updateDirection();
  986. }
  987. }
  988. /**
  989. * Clone the current sound in the scene.
  990. * @returns the new sound clone
  991. */
  992. clone() {
  993. if (!this._streaming) {
  994. const setBufferAndRun = () => {
  995. if (this._isReadyToPlay) {
  996. clonedSound._audioBuffer = this.getAudioBuffer();
  997. clonedSound._isReadyToPlay = true;
  998. if (clonedSound.autoplay) {
  999. clonedSound.play(0, this._offset, this._length);
  1000. }
  1001. }
  1002. else {
  1003. setTimeout(setBufferAndRun, 300);
  1004. }
  1005. };
  1006. const currentOptions = {
  1007. autoplay: this.autoplay,
  1008. loop: this.loop,
  1009. volume: this._volume,
  1010. spatialSound: this._spatialSound,
  1011. maxDistance: this.maxDistance,
  1012. useCustomAttenuation: this.useCustomAttenuation,
  1013. rolloffFactor: this.rolloffFactor,
  1014. refDistance: this.refDistance,
  1015. distanceModel: this.distanceModel,
  1016. };
  1017. const clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  1018. if (this.useCustomAttenuation) {
  1019. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  1020. }
  1021. clonedSound.setPosition(this._position);
  1022. clonedSound.setPlaybackRate(this._playbackRate);
  1023. setBufferAndRun();
  1024. return clonedSound;
  1025. }
  1026. // Can't clone a streaming sound
  1027. else {
  1028. return null;
  1029. }
  1030. }
  1031. /**
  1032. * Gets the current underlying audio buffer containing the data
  1033. * @returns the audio buffer
  1034. */
  1035. getAudioBuffer() {
  1036. return this._audioBuffer;
  1037. }
  1038. /**
  1039. * Gets the WebAudio AudioBufferSourceNode, lets you keep track of and stop instances of this Sound.
  1040. * @returns the source node
  1041. */
  1042. getSoundSource() {
  1043. return this._soundSource;
  1044. }
  1045. /**
  1046. * Gets the WebAudio GainNode, gives you precise control over the gain of instances of this Sound.
  1047. * @returns the gain node
  1048. */
  1049. getSoundGain() {
  1050. return this._soundGain;
  1051. }
  1052. /**
  1053. * Serializes the Sound in a JSON representation
  1054. * @returns the JSON representation of the sound
  1055. */
  1056. serialize() {
  1057. const serializationObject = {
  1058. name: this.name,
  1059. url: this._url,
  1060. autoplay: this.autoplay,
  1061. loop: this.loop,
  1062. volume: this._volume,
  1063. spatialSound: this._spatialSound,
  1064. maxDistance: this.maxDistance,
  1065. rolloffFactor: this.rolloffFactor,
  1066. refDistance: this.refDistance,
  1067. distanceModel: this.distanceModel,
  1068. playbackRate: this._playbackRate,
  1069. panningModel: this._panningModel,
  1070. soundTrackId: this.soundTrackId,
  1071. metadata: this.metadata,
  1072. };
  1073. if (this._spatialSound) {
  1074. if (this._connectedTransformNode) {
  1075. serializationObject.connectedMeshId = this._connectedTransformNode.id;
  1076. }
  1077. serializationObject.position = this._position.asArray();
  1078. serializationObject.refDistance = this.refDistance;
  1079. serializationObject.distanceModel = this.distanceModel;
  1080. serializationObject.isDirectional = this._isDirectional;
  1081. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  1082. serializationObject.coneInnerAngle = this._coneInnerAngle;
  1083. serializationObject.coneOuterAngle = this._coneOuterAngle;
  1084. serializationObject.coneOuterGain = this._coneOuterGain;
  1085. }
  1086. return serializationObject;
  1087. }
  1088. /**
  1089. * Parse a JSON representation of a sound to instantiate in a given scene
  1090. * @param parsedSound Define the JSON representation of the sound (usually coming from the serialize method)
  1091. * @param scene Define the scene the new parsed sound should be created in
  1092. * @param rootUrl Define the rooturl of the load in case we need to fetch relative dependencies
  1093. * @param sourceSound Define a sound place holder if do not need to instantiate a new one
  1094. * @returns the newly parsed sound
  1095. */
  1096. static Parse(parsedSound, scene, rootUrl, sourceSound) {
  1097. const soundName = parsedSound.name;
  1098. let soundUrl;
  1099. if (parsedSound.url) {
  1100. soundUrl = rootUrl + parsedSound.url;
  1101. }
  1102. else {
  1103. soundUrl = rootUrl + soundName;
  1104. }
  1105. const options = {
  1106. autoplay: parsedSound.autoplay,
  1107. loop: parsedSound.loop,
  1108. volume: parsedSound.volume,
  1109. spatialSound: parsedSound.spatialSound,
  1110. maxDistance: parsedSound.maxDistance,
  1111. rolloffFactor: parsedSound.rolloffFactor,
  1112. refDistance: parsedSound.refDistance,
  1113. distanceModel: parsedSound.distanceModel,
  1114. playbackRate: parsedSound.playbackRate,
  1115. };
  1116. let newSound;
  1117. if (!sourceSound) {
  1118. newSound = new Sound(soundName, soundUrl, scene, () => {
  1119. scene.removePendingData(newSound);
  1120. }, options);
  1121. scene.addPendingData(newSound);
  1122. }
  1123. else {
  1124. const setBufferAndRun = () => {
  1125. if (sourceSound._isReadyToPlay) {
  1126. newSound._audioBuffer = sourceSound.getAudioBuffer();
  1127. newSound._isReadyToPlay = true;
  1128. if (newSound.autoplay) {
  1129. newSound.play(0, newSound._offset, newSound._length);
  1130. }
  1131. }
  1132. else {
  1133. setTimeout(setBufferAndRun, 300);
  1134. }
  1135. };
  1136. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  1137. setBufferAndRun();
  1138. }
  1139. if (parsedSound.position) {
  1140. const soundPosition = Vector3.FromArray(parsedSound.position);
  1141. newSound.setPosition(soundPosition);
  1142. }
  1143. if (parsedSound.isDirectional) {
  1144. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  1145. if (parsedSound.localDirectionToMesh) {
  1146. const localDirectionToMesh = Vector3.FromArray(parsedSound.localDirectionToMesh);
  1147. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  1148. }
  1149. }
  1150. if (parsedSound.connectedMeshId) {
  1151. const connectedMesh = scene.getMeshById(parsedSound.connectedMeshId);
  1152. if (connectedMesh) {
  1153. newSound.attachToMesh(connectedMesh);
  1154. }
  1155. }
  1156. if (parsedSound.metadata) {
  1157. newSound.metadata = parsedSound.metadata;
  1158. }
  1159. return newSound;
  1160. }
  1161. _setOffset(value) {
  1162. if (this._offset === value) {
  1163. return;
  1164. }
  1165. if (this.isPaused) {
  1166. this.stop();
  1167. this.isPaused = false;
  1168. }
  1169. this._offset = value;
  1170. }
  1171. _clearTimeoutsAndObservers() {
  1172. if (this._tryToPlayTimeout) {
  1173. clearTimeout(this._tryToPlayTimeout);
  1174. this._tryToPlayTimeout = null;
  1175. }
  1176. if (this._audioUnlockedObserver) {
  1177. Engine.audioEngine?.onAudioUnlockedObservable.remove(this._audioUnlockedObserver);
  1178. this._audioUnlockedObserver = null;
  1179. }
  1180. }
  1181. }
  1182. /**
  1183. * @internal
  1184. */
  1185. Sound._SceneComponentInitialization = (_) => {
  1186. throw _WarnImport("AudioSceneComponent");
  1187. };
  1188. //# sourceMappingURL=sound.js.map