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 * demo: 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 Audio playing manager. 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 * Activate audio function. Note: Require user action events to activate. Currently support WebAudio. 34 */ 35 enableAudio: function(){ 36 if(WebAudio.isSupported){ 37 WebAudio.enable(); 38 } 39 }, 40 41 /** 42 * Get audio element. Default use WebAudio if supported. 43 * @param {String|Object} source If String, it's the source of the audio; If Object, it should contains a src property. 44 * @param {Boolean} [preferWebAudio=true] Whether or not to use WebAudio first, default is true. 45 * @returns {WebAudio|HTMLAudio} Audio playing instance. 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 * Remove audio element. 68 * @param {String|Object} source If String, it's the source of the audio; If Object, it should contains a src property. 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 };