babylon.sound.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. var BABYLON;
  2. (function (BABYLON) {
  3. var Sound = (function () {
  4. /**
  5. * Create a sound and attach it to a scene
  6. * @param name Name of your sound
  7. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  8. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  9. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  10. */
  11. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  12. var _this = this;
  13. this.autoplay = false;
  14. this.loop = false;
  15. this.useCustomAttenuation = false;
  16. this.spatialSound = false;
  17. this.refDistance = 1;
  18. this.rolloffFactor = 1;
  19. this.maxDistance = 100;
  20. this.distanceModel = "linear";
  21. this._panningModel = "equalpower";
  22. this._playbackRate = 1;
  23. this._startTime = 0;
  24. this._startOffset = 0;
  25. this._position = BABYLON.Vector3.Zero();
  26. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  27. this._volume = 1;
  28. this._isLoaded = false;
  29. this._isReadyToPlay = false;
  30. this.isPlaying = false;
  31. this.isPaused = false;
  32. this._isDirectional = false;
  33. // Used if you'd like to create a directional sound.
  34. // If not set, the sound will be omnidirectional
  35. this._coneInnerAngle = 360;
  36. this._coneOuterAngle = 360;
  37. this._coneOuterGain = 0;
  38. this.name = name;
  39. this._scene = scene;
  40. this._readyToPlayCallback = readyToPlayCallback;
  41. // Default custom attenuation function is a linear attenuation
  42. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  43. if (currentDistance < maxDistance) {
  44. return currentVolume * (1 - currentDistance / maxDistance);
  45. }
  46. else {
  47. return 0;
  48. }
  49. };
  50. if (options) {
  51. this.autoplay = options.autoplay || false;
  52. this.loop = options.loop || false;
  53. // if volume === 0, we need another way to check this option
  54. if (options.volume !== undefined) {
  55. this._volume = options.volume;
  56. }
  57. this.spatialSound = options.spatialSound || false;
  58. this.maxDistance = options.maxDistance || 100;
  59. this.useCustomAttenuation = options.useCustomAttenuation || false;
  60. this.rolloffFactor = options.rolloffFactor || 1;
  61. this.refDistance = options.refDistance || 1;
  62. this.distanceModel = options.distanceModel || "linear";
  63. this._playbackRate = options.playbackRate || 1;
  64. }
  65. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  66. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  67. this._soundGain.gain.value = this._volume;
  68. this._inputAudioNode = this._soundGain;
  69. this._ouputAudioNode = this._soundGain;
  70. if (this.spatialSound) {
  71. this._createSpatialParameters();
  72. }
  73. this._scene.mainSoundTrack.AddSound(this);
  74. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  75. if (urlOrArrayBuffer) {
  76. // If it's an URL
  77. if (typeof (urlOrArrayBuffer) === "string") {
  78. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) {
  79. _this._soundLoaded(data);
  80. }, null, null, true);
  81. }
  82. else {
  83. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  84. this._soundLoaded(urlOrArrayBuffer);
  85. }
  86. else {
  87. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  88. }
  89. }
  90. }
  91. }
  92. else {
  93. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  94. this._scene.mainSoundTrack.AddSound(this);
  95. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  96. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  97. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  98. }
  99. if (this._readyToPlayCallback) {
  100. this._readyToPlayCallback();
  101. }
  102. }
  103. }
  104. Sound.prototype.dispose = function () {
  105. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  106. if (this.isPlaying) {
  107. this.stop();
  108. }
  109. this._isReadyToPlay = false;
  110. if (this.soundTrackId === -1) {
  111. this._scene.mainSoundTrack.RemoveSound(this);
  112. }
  113. else {
  114. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  115. }
  116. if (this._soundGain) {
  117. this._soundGain.disconnect();
  118. this._soundGain = null;
  119. }
  120. if (this._soundPanner) {
  121. this._soundPanner.disconnect();
  122. this._soundPanner = null;
  123. }
  124. if (this._soundSource) {
  125. this._soundSource.disconnect();
  126. this._soundSource = null;
  127. }
  128. this._audioBuffer = null;
  129. if (this._connectedMesh) {
  130. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  131. this._connectedMesh = null;
  132. }
  133. }
  134. };
  135. Sound.prototype._soundLoaded = function (audioData) {
  136. var _this = this;
  137. this._isLoaded = true;
  138. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  139. _this._audioBuffer = buffer;
  140. _this._isReadyToPlay = true;
  141. if (_this.autoplay) {
  142. _this.play();
  143. }
  144. if (_this._readyToPlayCallback) {
  145. _this._readyToPlayCallback();
  146. }
  147. }, function (error) {
  148. BABYLON.Tools.Error("Error while decoding audio data: " + error.err);
  149. });
  150. };
  151. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  152. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  153. this._audioBuffer = audioBuffer;
  154. this._isReadyToPlay = true;
  155. }
  156. };
  157. Sound.prototype.updateOptions = function (options) {
  158. if (options) {
  159. this.loop = options.loop || this.loop;
  160. this.maxDistance = options.maxDistance || this.maxDistance;
  161. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  162. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  163. this.refDistance = options.refDistance || this.refDistance;
  164. this.distanceModel = options.distanceModel || this.distanceModel;
  165. this._playbackRate = options.playbackRate || this._playbackRate;
  166. }
  167. };
  168. Sound.prototype._createSpatialParameters = function () {
  169. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  170. if (this._scene.headphone) {
  171. this._panningModel = "HRTF";
  172. }
  173. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  174. if (this.useCustomAttenuation) {
  175. // Tricks to disable in a way embedded Web Audio attenuation
  176. this._soundPanner.distanceModel = "linear";
  177. this._soundPanner.maxDistance = Number.MAX_VALUE;
  178. this._soundPanner.refDistance = 1;
  179. this._soundPanner.rolloffFactor = 1;
  180. this._soundPanner.panningModel = this._panningModel;
  181. }
  182. else {
  183. this._soundPanner.distanceModel = this.distanceModel;
  184. this._soundPanner.maxDistance = this.maxDistance;
  185. this._soundPanner.refDistance = this.refDistance;
  186. this._soundPanner.rolloffFactor = this.rolloffFactor;
  187. this._soundPanner.panningModel = this._panningModel;
  188. }
  189. this._soundPanner.connect(this._ouputAudioNode);
  190. this._inputAudioNode = this._soundPanner;
  191. }
  192. };
  193. Sound.prototype.switchPanningModelToHRTF = function () {
  194. this._panningModel = "HRTF";
  195. this._switchPanningModel();
  196. };
  197. Sound.prototype.switchPanningModelToEqualPower = function () {
  198. this._panningModel = "equalpower";
  199. this._switchPanningModel();
  200. };
  201. Sound.prototype._switchPanningModel = function () {
  202. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  203. this._soundPanner.panningModel = this._panningModel;
  204. }
  205. };
  206. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  207. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  208. this._ouputAudioNode.disconnect();
  209. this._ouputAudioNode.connect(soundTrackAudioNode);
  210. }
  211. };
  212. /**
  213. * Transform this sound into a directional source
  214. * @param coneInnerAngle Size of the inner cone in degree
  215. * @param coneOuterAngle Size of the outer cone in degree
  216. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  217. */
  218. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  219. if (coneOuterAngle < coneInnerAngle) {
  220. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  221. return;
  222. }
  223. this._coneInnerAngle = coneInnerAngle;
  224. this._coneOuterAngle = coneOuterAngle;
  225. this._coneOuterGain = coneOuterGain;
  226. this._isDirectional = true;
  227. if (this.isPlaying && this.loop) {
  228. this.stop();
  229. this.play();
  230. }
  231. };
  232. Sound.prototype.setPosition = function (newPosition) {
  233. this._position = newPosition;
  234. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  235. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  236. }
  237. };
  238. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  239. this._localDirection = newLocalDirection;
  240. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  241. this._updateDirection();
  242. }
  243. };
  244. Sound.prototype._updateDirection = function () {
  245. var mat = this._connectedMesh.getWorldMatrix();
  246. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  247. direction.normalize();
  248. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  249. };
  250. Sound.prototype.updateDistanceFromListener = function () {
  251. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  252. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  253. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  254. }
  255. };
  256. Sound.prototype.setAttenuationFunction = function (callback) {
  257. this._customAttenuationFunction = callback;
  258. };
  259. /**
  260. * Play the sound
  261. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  262. */
  263. Sound.prototype.play = function (time) {
  264. var _this = this;
  265. if (this._isReadyToPlay && this._scene.audioEnabled) {
  266. try {
  267. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  268. if (!this._soundSource) {
  269. if (this.spatialSound) {
  270. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  271. if (this._isDirectional) {
  272. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  273. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  274. this._soundPanner.coneOuterGain = this._coneOuterGain;
  275. if (this._connectedMesh) {
  276. this._updateDirection();
  277. }
  278. else {
  279. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  280. }
  281. }
  282. }
  283. }
  284. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  285. this._soundSource.buffer = this._audioBuffer;
  286. this._soundSource.connect(this._inputAudioNode);
  287. this._soundSource.loop = this.loop;
  288. this._soundSource.playbackRate.value = this._playbackRate;
  289. this._startTime = startTime;
  290. this._soundSource.onended = function () {
  291. _this._onended();
  292. };
  293. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  294. this.isPlaying = true;
  295. this.isPaused = false;
  296. }
  297. catch (ex) {
  298. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  299. }
  300. }
  301. };
  302. Sound.prototype._onended = function () {
  303. this.isPlaying = false;
  304. if (this.onended) {
  305. this.onended();
  306. }
  307. };
  308. /**
  309. * Stop the sound
  310. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  311. */
  312. Sound.prototype.stop = function (time) {
  313. if (this.isPlaying) {
  314. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  315. this._soundSource.stop(stopTime);
  316. this.isPlaying = false;
  317. }
  318. };
  319. Sound.prototype.pause = function () {
  320. if (this.isPlaying) {
  321. this.stop(0);
  322. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  323. this.isPaused = true;
  324. }
  325. };
  326. Sound.prototype.setVolume = function (newVolume, time) {
  327. if (BABYLON.Engine.audioEngine.canUseWebAudio && !this.spatialSound) {
  328. if (time) {
  329. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  330. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  331. }
  332. else {
  333. this._soundGain.gain.value = newVolume;
  334. }
  335. }
  336. this._volume = newVolume;
  337. };
  338. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  339. this._playbackRate = newPlaybackRate;
  340. if (this.isPlaying) {
  341. this._soundSource.playbackRate.value = this._playbackRate;
  342. }
  343. };
  344. Sound.prototype.getVolume = function () {
  345. return this._volume;
  346. };
  347. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  348. var _this = this;
  349. this._connectedMesh = meshToConnectTo;
  350. if (!this.spatialSound) {
  351. this._createSpatialParameters();
  352. this.spatialSound = true;
  353. if (this.isPlaying && this.loop) {
  354. this.stop();
  355. this.play();
  356. }
  357. }
  358. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  359. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  360. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  361. };
  362. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  363. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  364. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  365. this._updateDirection();
  366. }
  367. };
  368. return Sound;
  369. })();
  370. BABYLON.Sound = Sound;
  371. })(BABYLON || (BABYLON = {}));
  372. //# sourceMappingURL=babylon.sound.js.map