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