Music.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // Music.js
  2. // Background Music support for iPhone, iPad
  3. // FZ, Copyright (c) 2010 Zlongames
  4. (function()
  5. {
  6. FZ.Music = {
  7. theAudio:null,
  8. theIntervalId:0,
  9. isMute:false,
  10. set: function(theAudio, loop)
  11. {
  12. this.loop = Boolean(loop);
  13. this.theAudio = theAudio;
  14. theAudio.loop = loop;
  15. },
  16. setMute:function(isMute)
  17. {
  18. this.isMute = isMute;
  19. if (this.isMute) {
  20. this.stop();
  21. }
  22. else {
  23. this.play();
  24. }
  25. },
  26. play: function()
  27. {
  28. if (this.isMute)
  29. return;
  30. this.stop();
  31. this.theAudio.play();
  32. if (this.theAudio.duration)
  33. {
  34. if (this.loop){
  35. this.theIntervalId = window.setInterval(this.replay, Math.floor(this.theAudio.duration * 1000) -1000 );
  36. }
  37. // this.theIntervalId = window.setInterval(FZ.Tools.bind(this,this.replay), Math.floor(this.theAudio.duration * 1000) -1000 );
  38. else{
  39. window.setTimeout(function(){this.theAudio.pause();try{ this.theAudio.currentTime=0;}catch(e){};}, Math.floor(this.theAudio.duration * 1000) -1000);
  40. }
  41. }
  42. },
  43. stop: function()
  44. {
  45. if (!this.theAudio) return;
  46. this.theAudio.pause();
  47. try{
  48. this.theAudio.currentTime = 0;
  49. } catch(e){};
  50. window.clearInterval(this.theIntervalId);
  51. },
  52. replay:function()
  53. {
  54. FZ.Music.stop();
  55. FZ.Music.play();
  56. },
  57. pageHide: function(e)
  58. {
  59. if (FZ.Music.theAudio) FZ.Music.stop();
  60. },
  61. pageShow: function(e)
  62. {
  63. if (FZ.Music.theAudio) FZ.Music.play();
  64. }
  65. };
  66. window.addEventListener("pagehide", FZ.Music.pageHide, false);
  67. window.addEventListener("pageshow", FZ.Music.pageShow, false);
  68. })();