1 goog.provide('lime.audio.Audio');
  2 
  3 goog.require('goog.events');
  4 
  5 // Notice. Real problems for audio in iOS. Works only for one sound
  6 // and needs to be initialized from user event. No solutions found.
  7 
  8 /**
  9  * Audio stream object
 10  * @constructor
 11  * @param {string} filePath Path to audio file.
 12  */
 13 lime.audio.Audio = function(filePath) {
 14 
 15     
 16     if(filePath && goog.isFunction(filePath.data)){
 17         filePath = filePath.data();
 18     }
 19 
 20     /**
 21      * @type bBoolean}
 22      * @private
 23      */
 24     this.loaded_ = false;
 25 
 26     /**
 27      * @type {boolean}
 28      * @private
 29      */
 30     this.playing_ = false;
 31 
 32     /**
 33      * Internal audio element
 34      * @type {audio}
 35      */
 36     this.baseElement = document.createElement('audio');
 37     this.baseElement.preload = true;
 38     this.baseElement.loop = false;
 39 
 40     if (goog.userAgent.GECKO && (/\.mp3$/).test(filePath)) {
 41         filePath = filePath.replace(/\.mp3$/, '.ogg');
 42     }
 43 
 44     this.baseElement.src = filePath;
 45     this.baseElement.load();
 46 
 47     this.loadInterval = setInterval(goog.bind(this.loadHandler_, this), 10);
 48 
 49     this.loaded_ = false;
 50 };
 51 
 52 /**
 53  * Handle loading the audio file. Event handlers seem to fail
 54  * on lot of browsers.
 55  * @private
 56  */
 57 lime.audio.Audio.prototype.loadHandler_ = function() {
 58     if (this.baseElement.readyState > 2) {
 59         this.loaded_ = true;
 60         clearTimeout(this.loadInterval);
 61     }
 62     if (this.baseElement.error)clearTimeout(this.loadInterval);
 63 
 64     if (lime.userAgent.IOS && this.baseElement.readyState == 0) {
 65         //ios hack do not work any more after 4.2.1 updates
 66         // no good solutions that i know
 67         this.loaded_ = true;
 68         clearTimeout(this.loadInterval);
 69         // this means that ios audio anly works if called from user action
 70     }
 71 };
 72 
 73 /**
 74  * Returns true if audio file has been loaded
 75  * @return {boolean} Audio has been loaded.
 76  */
 77 lime.audio.Audio.prototype.isLoaded = function() {
 78     return this.loaded_;
 79 };
 80 
 81 /**
 82  * Returns true if audio file is playing
 83  * @return {boolean} Audio is playing.
 84  */
 85 lime.audio.Audio.prototype.isPlaying = function() {
 86     return this.playing_;
 87 };
 88 
 89 /**
 90  * Start playing the audio
 91  */
 92 lime.audio.Audio.prototype.play = function() {
 93     if (this.isLoaded() && !this.isPlaying()) {
 94         this.baseElement.play();
 95         this.playing_ = true;
 96     }
 97 };
 98 
 99 /**
100  * Stop playing the audio
101  */
102 lime.audio.Audio.prototype.stop = function() {
103     if (this.isPlaying()) {
104         this.baseElement.pause();
105         this.playing_ = false;
106     }
107 };
108 
109 
110