Zalerinian

HTML5Audio Fallback

Dec 6th, 2015
286
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*:
  2.  * @plugindesc Makes the HTML5Audio fallback a more viable option for games.
  3.  * @author Zalerinian
  4.  *
  5.  * @help
  6.  * ==============================================================================
  7.  *    Support
  8.  * ==============================================================================
  9.  *
  10.  * Have an issue, question, or suggestion? My preferred method of contact would
  11.  * be on the RMW forums, preferably by posing in one of my topics, but if you
  12.  * really need to reach me directly, feel free to PM me, or send me an email
  13.  * using the address below.
  14.  *
  15.  * Author: Zalerinian
  16.  * email: support at razelon.com
  17.  *
  18.  * ==============================================================================
  19.  *
  20.  * This plugin is, currently, very rushed/makeshift. I didn't really do a lot of
  21.  * testing to make sure it worked perfectly in every situation, but it should be
  22.  * enough to get things working.
  23.  *
  24.  * Please note, this plugin overwrites several functions in the AudioManager
  25.  * class to fix some issues with it working with HTML5Audio. For that reason, I
  26.  * recommend that this plugin be moved to the top, or relatively to the top, of
  27.  * your plugins. This will help ensure that any plugins that aliased the
  28.  * overwritten functions are not broken.
  29.  *
  30.  * If you have any issues using this plugin, please contact me via the methods in
  31.  * the support section above.
  32.  *
  33.  * As of right now, unless there are issues with how the plugin currently is, I
  34.  * am not sure if I plan to continue working on it.
  35.  */
  36. var Imported = Imported || {};
  37.  
  38. var Zale = Zale || {};
  39. Zale.HTML5Audio = {};
  40.  
  41. (function() {
  42.   if(Imported.MVCommons) {
  43.     var author = [{
  44.       email: "[email protected]",
  45.       name: "Zalerinian",
  46.       website: "http://www.razelon.com"
  47.       }];
  48.     var v = PluginManager.register("HTML5Audio Fallback", "1.0.0", PluginManager.getBasicPlugin("HTML5Audio Fallback").description, author, "2015-12-06");
  49.     if (v === false){
  50.       PluginManager.printPlugin("HTML5Audio Fallback");
  51.       throw new Error("Unable to load HTML5Audio Fallback due to registration failure! Is there another version running?");
  52.     }
  53.   } else {
  54.     Imported["HTML5Audio Fallback"] = "1.0.0";
  55.   }
  56. })();
  57.  
  58.  
  59. //-----------------------------------------------------------------------------
  60. /**
  61.  * The static class that handles HTML5 Audio.
  62.  *
  63.  * @class Html5Audio
  64.  * @constructor
  65.  */
  66. function Html5Audio() {
  67.   this.initialize.apply(this, arguments);
  68. }
  69.  
  70. Html5Audio.prototype.constructor = Html5Audio;
  71. Html5Audio._unlocked = Utils.isNwjs();
  72.  
  73. /**
  74.  * Sets up the Html5 Audio.
  75.  *
  76.  * @static
  77.  * @method setup
  78.  * @param {String} url The url of the audio file
  79.  */
  80. Html5Audio.prototype.setup = function (url) {
  81.   if (!this._initialized) {
  82.     this.initialize();
  83.   }
  84.   this.clear();
  85.   this._url = url;
  86. };
  87.  
  88. /**
  89.  * Initializes the audio system.
  90.  *
  91.  * @static
  92.  * @method initialize
  93.  * @return {Boolean} True if the audio system is available
  94.  */
  95. Html5Audio.prototype.initialize = function (url) {
  96.   if (!this._initialized) {
  97.     this._initialized = false;
  98.     this._audioElement = null;
  99.     this._gainTweenInterval = null;
  100.     this._tweenGain = 0;
  101.     this._tweenTargetGain = 0;
  102.     this._tweenGainStep = 0;
  103.     this._staticSePath = null;
  104.     if (!this._audioElement) {
  105.       try {
  106.         this._audioElement = new Audio();
  107.       } catch (e) {
  108.         console.error(e);
  109.         this._audioElement = null;
  110.       }
  111.     }
  112.     if (!!this._audioElement) {
  113.       this._setupEventHandlers();
  114.       document.getElementsByTagName('body')[0].appendChild(this._audioElement);
  115.     }
  116.     this._initialized = true;
  117.   }
  118.   if(!!url) {
  119.     this.setup(url);
  120.   }
  121.   return !!this._audioElement;
  122. };
  123.  
  124. /**
  125.  * @static
  126.  * @method _setupEventHandlers
  127.  * @private
  128.  */
  129. Html5Audio.prototype._setupEventHandlers = function () {
  130.   document.addEventListener('touchstart', this._onTouchStart.bind(this));
  131.   document.addEventListener('visibilitychange', this._onVisibilityChange.bind(this));
  132.   this._audioElement.addEventListener("canplaythrough", this._onLoadedData.bind(this));
  133.   this._audioElement.addEventListener("error", this._onError.bind(this));
  134.   this._audioElement.addEventListener("ended", this._onEnded.bind(this));
  135. };
  136.  
  137. /**
  138.  * @static
  139.  * @method _onTouchStart
  140.  * @private
  141.  */
  142. Html5Audio.prototype._onTouchStart = function () {
  143.   if (this._audioElement && !Html5Audio._unlocked) {
  144.     if (this._isLoading) {
  145.       this._load(this._url);
  146.       Html5Audio._unlocked = true;
  147.     } else {
  148.       if (this._staticSePath) {
  149.         this._audioElement.src = this._staticSePath;
  150.         this._audioElement.volume = 0;
  151.         this._audioElement.loop = false;
  152.         this._audioElement.play();
  153.         Html5Audio._unlocked = true;
  154.       }
  155.     }
  156.   }
  157. };
  158.  
  159. /**
  160.  * @static
  161.  * @method _onVisibilityChange
  162.  * @private
  163.  */
  164. Html5Audio.prototype._onVisibilityChange = function () {
  165.   if (document.visibilityState === 'hidden') {
  166.     this._onHide();
  167.   } else {
  168.     this._onShow();
  169.   }
  170. };
  171.  
  172. /**
  173.  * @static
  174.  * @method _onLoadedData
  175.  * @private
  176.  */
  177. Html5Audio.prototype._onLoadedData = function () {
  178.   this._buffered = true;
  179.   if (Html5Audio._unlocked) this._onLoad();
  180. };
  181.  
  182. /**
  183.  * @static
  184.  * @method _onError
  185.  * @private
  186.  */
  187. Html5Audio.prototype._onError = function () {
  188.   this.__error = arguments;
  189.   this._hasError = true;
  190. };
  191.  
  192. /**
  193.  * @static
  194.  * @method _onEnded
  195.  * @private
  196.  */
  197. Html5Audio.prototype._onEnded = function () {
  198.   if (!this._audioElement.loop) {
  199.     this.stop();
  200.       while (this._stopListeners.length > 0) {
  201.       var listener = this._stopListeners.shift();
  202.       listener();
  203.     }
  204.   }
  205. };
  206.  
  207. /**
  208.  * @static
  209.  * @method _onHide
  210.  * @private
  211.  */
  212. Html5Audio.prototype._onHide = function () {
  213.   this._audioElement.volume = 0;
  214.   this._tweenGain = 0;
  215. };
  216.  
  217. /**
  218.  * @static
  219.  * @method _onShow
  220.  * @private
  221.  */
  222. Html5Audio.prototype._onShow = function () {
  223.   this.fadeIn(0.5);
  224. };
  225.  
  226. /**
  227.  * Clears the audio data.
  228.  *
  229.  * @static
  230.  * @method clear
  231.  */
  232. Html5Audio.prototype.clear = function () {
  233.   this.stop();
  234.   this._volume = 1;
  235.   this._loadListeners = [];
  236.   this._stopListeners = [];
  237.   this._hasError = false;
  238.   this._autoPlay = false;
  239.   this._isLoading = false;
  240.   this._buffered = false;
  241. };
  242.  
  243. /**
  244.  * Set the URL of static se.
  245.  *
  246.  * @static
  247.  * @param {String} url
  248.  */
  249. Html5Audio.prototype.setStaticSe = function (url) {
  250.   if (!this._initialized) {
  251.     this.initialize();
  252.     this.clear();
  253.   }
  254.   this._staticSePath = url;
  255. };
  256.  
  257. /**
  258.  * [read-only] The url of the audio file.
  259.  *
  260.  * @property url
  261.  * @type String
  262.  */
  263. Object.defineProperty(Html5Audio.prototype, 'url', {
  264.   get: function () {
  265.     return this._url;
  266.   },
  267.   configurable: true
  268. });
  269.  
  270. /**
  271.  * The volume of the audio.
  272.  *
  273.  * @property volume
  274.  * @type Number
  275.  */
  276. Object.defineProperty(Html5Audio.prototype, 'volume', {
  277.   get: function () {
  278.     return this._volume;
  279.   },
  280.   set: function (value) {
  281.     this._volume = value;
  282.     if (this._audioElement) {
  283.       this._audioElement.volume = this.volume;
  284.     }
  285.   },
  286.   configurable: true
  287. });
  288.  
  289. /**
  290.  * Checks whether the audio data is ready to play.
  291.  *
  292.  * @static
  293.  * @method isReady
  294.  * @return {Boolean} True if the audio data is ready to play
  295.  */
  296. Html5Audio.prototype.isReady = function () {
  297.   return this._buffered;
  298. };
  299.  
  300. /**
  301.  * Checks whether a loading error has occurred.
  302.  *
  303.  * @static
  304.  * @method isError
  305.  * @return {Boolean} True if a loading error has occurred
  306.  */
  307. Html5Audio.prototype.isError = function () {
  308.   return this._hasError;
  309. };
  310.  
  311. /**
  312.  * Checks whether the audio is playing.
  313.  *
  314.  * @static
  315.  * @method isPlaying
  316.  * @return {Boolean} True if the audio is playing
  317.  */
  318. Html5Audio.prototype.isPlaying = function () {
  319.   return !this._audioElement.paused;
  320. };
  321.  
  322. /**
  323.  * Plays the audio.
  324.  *
  325.  * @static
  326.  * @method play
  327.  * @param {Boolean} loop Whether the audio data play in a loop
  328.  * @param {Number} offset The start position to play in seconds
  329.  */
  330. Html5Audio.prototype.play = function (loop, offset) {
  331.   if (this.isReady()) {
  332.     offset = offset || 0;
  333.     this._startPlaying(loop, offset);
  334.   } else if (this._audioElement) {
  335.     this._autoPlay = true;
  336.     this.addLoadListener(function () {
  337.       if (this._autoPlay) {
  338.         this.play(loop, offset);
  339.         if (this._gainTweenInterval) {
  340.           clearInterval(this._gainTweenInterval);
  341.           this._gainTweenInterval = null;
  342.         }
  343.       }
  344.     }.bind(this));
  345.     if (!this._isLoading) this._load(this._url);
  346.   }
  347. };
  348.  
  349. /**
  350.  * Stops the audio.
  351.  *
  352.  * @static
  353.  * @method stop
  354.  */
  355. Html5Audio.prototype.stop = function () {
  356.   if (this._audioElement) this._audioElement.pause();
  357.   this._autoPlay = false;
  358.   if (this._tweenInterval) {
  359.     clearInterval(this._tweenInterval);
  360.     this._tweenInterval = null;
  361.     this._audioElement.volume = 0;
  362.   }
  363. };
  364.  
  365. Html5Audio.prototype.cleanUp = function() {
  366.   try {
  367.     document.getElementsByTagName('body')[0].removeChild(this._audioElement);
  368.   } catch(e) {
  369.     console.warn("The audio element with the file " + this._url + " appears to have already been removed.");
  370.   }
  371. }
  372.  
  373. /**
  374.  * Performs the audio fade-in.
  375.  *
  376.  * @static
  377.  * @method fadeIn
  378.  * @param {Number} duration Fade-in time in seconds
  379.  */
  380. Html5Audio.prototype.fadeIn = function (duration) {
  381.   if (this.isReady()) {
  382.     if (this._audioElement) {
  383.       this._tweenTargetGain = this._volume;
  384.       this._tweenGain = 0;
  385.       this._startGainTween(duration);
  386.     }
  387.   } else if (this._autoPlay) {
  388.     this.addLoadListener(function () {
  389.       this.fadeIn(duration);
  390.     }.bind(this));
  391.   }
  392. };
  393.  
  394. /**
  395.  * Performs the audio fade-out.
  396.  *
  397.  * @static
  398.  * @method fadeOut
  399.  * @param {Number} duration Fade-out time in seconds
  400.  */
  401. Html5Audio.prototype.fadeOut = function (duration) {
  402.   if (this._audioElement) {
  403.     this._tweenTargetGain = 0;
  404.     this._tweenGain = this._volume;
  405.     this._startGainTween(duration);
  406.   }
  407. };
  408.  
  409. /**
  410.  * Gets the seek position of the audio.
  411.  *
  412.  * @static
  413.  * @method seek
  414.  */
  415. Html5Audio.prototype.seek = function () {
  416.   if (this._audioElement) {
  417.     return this._audioElement.currentTime;
  418.   } else {
  419.     return 0;
  420.   }
  421. };
  422.  
  423. /**
  424.  * Add a callback function that will be called when the audio data is loaded.
  425.  *
  426.  * @static
  427.  * @method addLoadListener
  428.  * @param {Function} listner The callback function
  429.  */
  430. Html5Audio.prototype.addLoadListener = function (listner) {
  431.   this._loadListeners.push(listner);
  432. };
  433.  
  434. Html5Audio.prototype.addStopListener = function(listener) {
  435.   this._stopListeners.push(listener);
  436. }
  437.  
  438. /**
  439.  * @static
  440.  * @method _load
  441.  * @param {String} url
  442.  * @private
  443.  */
  444. Html5Audio.prototype._load = function (url) {
  445.   if (this._audioElement) {
  446.     this._isLoading = true;
  447.     this._audioElement.src = url;
  448.     this._audioElement.load();
  449.   }
  450. };
  451.  
  452. /**
  453.  * @static
  454.  * @method _startPlaying
  455.  * @param {Boolean} loop
  456.  * @param {Number} offset
  457.  * @private
  458.  */
  459. Html5Audio.prototype._startPlaying = function (loop, offset) {
  460.   this._audioElement.loop = loop;
  461.   if (this._gainTweenInterval) {
  462.     clearInterval(this._gainTweenInterval);
  463.     this._gainTweenInterval = null;
  464.   }
  465.   if (this._audioElement) {
  466.     this._audioElement.volume = this._volume;
  467.     this._audioElement.currentTime = offset;
  468.     this._audioElement.play();
  469.   }
  470. };
  471.  
  472. /**
  473.  * @static
  474.  * @method _onLoad
  475.  * @private
  476.  */
  477. Html5Audio.prototype._onLoad = function () {
  478.   this._isLoading = false;
  479.   while (this._loadListeners.length > 0) {
  480.     var listener = this._loadListeners.shift();
  481.     listener();
  482.   }
  483. };
  484.  
  485. /**
  486.  * @static
  487.  * @method _startGainTween
  488.  * @params {Number} duration
  489.  * @private
  490.  */
  491. Html5Audio.prototype._startGainTween = function (duration) {
  492.   this._audioElement.volume = this._tweenGain;
  493.   if (this._gainTweenInterval) {
  494.     clearInterval(this._gainTweenInterval);
  495.     this._gainTweenInterval = null;
  496.   }
  497.   this._tweenGainStep = (this._tweenTargetGain - this._tweenGain) / (60 * duration);
  498.   this._gainTweenInterval = setInterval(function () {
  499.     this._applyTweenValue(this._tweenTargetGain);
  500.   }.bind(this), 1000 / 60);
  501. };
  502.  
  503. /**
  504.  * @static
  505.  * @method _applyTweenValue
  506.  * @param {Number} volume
  507.  * @private
  508.  */
  509. Html5Audio.prototype._applyTweenValue = function (volume) {
  510.   this._tweenGain += this._tweenGainStep;
  511.   if (this._tweenGain < 0 && this._tweenGainStep < 0) {
  512.     this._tweenGain = 0;
  513.   }
  514.   else if (this._tweenGain > volume && this._tweenGainStep > 0) {
  515.     this._tweenGain = volume;
  516.   }
  517.  
  518.   if (Math.abs(this._tweenTargetGain - this._tweenGain) < 0.01) {
  519.     this._tweenGain = this._tweenTargetGain;
  520.     clearInterval(this._gainTweenInterval);
  521.     this._gainTweenInterval = null;
  522.   }
  523.  
  524.   this._audioElement.volume = this._tweenGain;
  525. };
  526.  
  527.  
  528.  
  529. SceneManager.initAudio = function() {
  530.   var noAudio = Utils.isOptionValid('noaudio');
  531.   if (!WebAudio.initialize(noAudio) && !noAudio) {
  532.     console.warn("Warning: The Web Audio API is not supported by your browser. Attempting to fall back to HTML5 audio...");
  533.   }
  534. };
  535.  
  536. AudioManager.createBuffer = function(folder, name) {
  537.   var ext = this.audioFileExt();
  538.   var url = this._path + folder + '/' + encodeURIComponent(name) + ext;
  539.   if (this.shouldUseHtml5Audio()) {
  540.     return new Html5Audio(url);
  541.   } else {
  542.     return new WebAudio(url);
  543.   }
  544. };
  545.  
  546. AudioManager.shouldUseHtml5Audio = function() {
  547.   // We use HTML5 Audio to play BGM instead of Web Audio API
  548.   // because decodeAudioData() is very slow on Android Chrome.
  549.   if(!WebAudio._initialized) {
  550.     WebAudio.initialize();
  551.   }
  552.   return (Utils.isAndroidChrome() || !WebAudio._context);
  553. };
  554.  
  555. AudioManager.playStaticSe = function(se) {
  556.   if (se.name) {
  557.     this.loadStaticSe(se);
  558.     for (var i = 0; i < this._staticBuffers.length; i++) {
  559.       var buffer = this._staticBuffers[i];
  560.       if (buffer._reservedSeName === se.name) {
  561.          buffer.stop();
  562.          this.updateSeParameters(buffer, se);
  563.          buffer.play(false);
  564.          break;
  565.       }
  566.     }
  567.   }
  568. };
  569.  
  570. AudioManager.loadStaticSe = function(se) {
  571.   if (se.name && !this.isStaticSe(se)) {
  572.     var buffer = this.createBuffer('se', se.name);
  573.     buffer._reservedSeName = se.name;
  574.     this._staticBuffers.push(buffer);
  575.     if (this.shouldUseHtml5Audio()) {
  576.       buffer.setStaticSe(buffer._url);
  577.     }
  578.   }
  579. };
  580.  
  581. AudioManager.audioFileExt = function() {
  582.   if ((WebAudio.canPlayOgg() || !WebAudio._context) && !Utils.isMobileDevice()) {
  583.     return '.ogg';
  584.   } else if(Utils.isInternetExplorer()) {
  585.     return ".mp3";
  586.   } else {
  587.     return '.m4a';
  588.   }
  589. };
  590.  
  591. AudioManager.checkWebAudioError = function(webAudio) {
  592.   if (webAudio && webAudio.isError() && !!WebAudio._context) {
  593.     throw new Error('Failed to load: ' + webAudio.url);
  594.   }
  595. };
  596.  
  597. Zale.HTML5Audio.AM_playse = AudioManager.playSe;
  598. AudioManager.playSe = function(se) {
  599.   if (se.name) {
  600.     this._seBuffers.forEach(function(audio) {
  601.       if(audio && this.shouldUseHtml5Audio() && !audio.isPlaying()) {
  602.         console.log("Cleaning up " + audio._url);
  603.         audio.cleanUp();
  604.       }
  605.     }, this);
  606.   }
  607.   Zale.HTML5Audio.AM_playse.call(this, se);
  608. };
  609.  
  610. Zale.HTML5Audio.AM_sse = AudioManager.stopSe;
  611. AudioManager.stopSe = function() {
  612.   this._seBuffers.forEach(function(audio) {
  613.     if(this.shouldUseHtml5Audio()) {
  614.       audio.cleanUp();
  615.     }
  616.   }, this)
  617. }
  618.  
  619. Zale.HTML5Audio.AM_sbgm = AudioManager.stopBgm;
  620. AudioManager.stopBgm = function() {
  621.   if(this.shouldUseHtml5Audio() && this._bgmBuffer) {
  622.     this._bgmBuffer.cleanUp();
  623.   }
  624.   Zale.HTML5Audio.AM_sbgm.call(this);
  625. }
  626.  
  627. Zale.HTML5Audio.AM_sbgs = AudioManager.stopBgs;
  628. AudioManager.stopBgs = function() {
  629.   if(this.shouldUseHtml5Audio() && this._bgsBuffer) {
  630.     this._bgsBuffer.cleanUp();
  631.   }
  632.   Zale.HTML5Audio.AM_sbgs.call(this);
  633. }
  634.  
  635. Zale.HTML5Audio.AM_sme = AudioManager.stopMe;
  636. AudioManager.stopMe = function() {
  637.   if(this.shouldUseHtml5Audio() && this._meBuffer) {
  638.     this._meBuffer.cleanUp();
  639.   }
  640.   Zale.HTML5Audio.AM_sme.call(this);
  641. }
  642.  
  643. Zale.HTML5Audio.SM_oss = SceneManager.onSceneStart;
  644. SceneManager.onSceneStart = function() {
  645.   Zale.HTML5Audio.SM_oss.call(this);
  646.   var tags = document.getElementsByTagName('audio');
  647.   if(!!tags) {
  648.     for(var i = tags.length; i >= 0; i--){
  649.       var audio = tags[i];
  650.       if(audio && AudioManager.shouldUseHtml5Audio() && audio.paused && audio.networkState !== 2) {
  651.         document.getElementsByTagName('body')[0].removeChild(audio);
  652.       }
  653.     }
  654.   }
  655. };
  656.  
  657. Utils.isInternetExplorer = function() {
  658.   return !!(navigator.userAgent.match(/Trident/i));
  659. }
Advertisement
Add Comment
Please, Sign In to add comment