1 /**
  2  * Hilo
  3  * Copyright 2015 alibaba.com
  4  * Licensed under the MIT License
  5  */
  6 
  7 /**
  8  * <iframe src='../../../examples/WebSound.html?noHeader' width = '320' height = '310' scrolling='no'></iframe>
  9  * <br/>
 10  * 使用示例:
 11  * <pre>
 12  * var audio = WebSound.getAudio({
 13  *     src: 'test.mp3',
 14  *     loop: false,
 15  *     volume: 1
 16  * }).on('load', function(e){
 17  *     console.log('load');
 18  * }).on('end', function(e){
 19  *     console.log('end');
 20  * }).play();
 21  * </pre>
 22  * @class 声音播放管理器。
 23  * @static
 24  * @module hilo/media/WebSound
 25  * @requires hilo/core/Hilo
 26  * @requires hilo/media/HTMLAudio
 27  * @requires hilo/media/WebAudio
 28  */
 29 var WebSound = {
 30     _audios: {},
 31 
 32     /**
 33      * 激活音频功能。注意:需用户事件触发此方法才有效。目前仅对WebAudio有效。
 34      */
 35     enableAudio: function(){
 36         if(WebAudio.isSupported){
 37             WebAudio.enable();
 38         }
 39     },
 40 
 41     /**
 42      * 获取音频对象。优先使用WebAudio。
 43      * @param {String|Object} source 若source为String,则为音频src地址;若为Object,则需包含src属性。
 44      * @returns {WebAudio|HTMLAudio} 音频播放对象实例。
 45      */
 46     getAudio: function(source){
 47         source = this._normalizeSource(source);
 48         var audio = this._audios[source.src];
 49         if(!audio){
 50             if(WebAudio.isSupported){
 51                 audio = new WebAudio(source);
 52             }else if(HTMLAudio.isSupported){
 53                 audio = new HTMLAudio(source);
 54             }
 55             this._audios[source.src] = audio;
 56         }
 57 
 58         return audio;
 59     },
 60 
 61     /**
 62      * 删除音频对象。
 63      * @param {String|Object} source 若source为String,则为音频src地址;若为Object,则需包含src属性。
 64      */
 65     removeAudio: function(source){
 66         var src = typeof source === 'string' ? source : source.src;
 67         var audio = this._audios[src];
 68         if(audio){
 69             audio.stop();
 70             audio.off();
 71             this._audios[src] = null;
 72             delete this._audios[src];
 73         }
 74     },
 75 
 76     /**
 77      * @private
 78      */
 79     _normalizeSource: function(source){
 80         var result = {};
 81         if(typeof source === 'string') result = {src:source};
 82         else Hilo.copy(result, source);
 83         return result;
 84     }
 85 
 86 };