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/media/HTMLAudio
 26  * @requires hilo/media/WebAudio
 27  * @requires hilo/util/util
 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      * @param {Boolean} [preferWebAudio=true] 是否优先使用WebAudio,默认 true 。
 45      * @returns {WebAudio|HTMLAudio} 音频播放对象实例。
 46      */
 47     getAudio: function(source, preferWebAudio){
 48         if(preferWebAudio === undefined){
 49             preferWebAudio = true;
 50         }
 51 
 52         source = this._normalizeSource(source);
 53         var audio = this._audios[source.src];
 54         if(!audio){
 55             if(preferWebAudio && WebAudio.isSupported){
 56                 audio = new WebAudio(source);
 57             }else if(HTMLAudio.isSupported){
 58                 audio = new HTMLAudio(source);
 59             }
 60             this._audios[source.src] = audio;
 61         }
 62 
 63         return audio;
 64     },
 65 
 66     /**
 67      * 删除音频对象。
 68      * @param {String|Object} source 若source为String,则为音频src地址;若为Object,则需包含src属性。
 69      */
 70     removeAudio: function(source){
 71         var src = typeof source === 'string' ? source : source.src;
 72         var audio = this._audios[src];
 73         if(audio){
 74             audio.stop();
 75             audio.off();
 76             this._audios[src] = null;
 77             delete this._audios[src];
 78         }
 79     },
 80 
 81     /**
 82      * @private
 83      */
 84     _normalizeSource: function(source){
 85         var result = {};
 86         if(typeof source === 'string') result = {src:source};
 87         else util.copy(result, source);
 88         return result;
 89     }
 90 
 91 };