1 /** 2 * Hilo 3 * Copyright 2015 alibaba.com 4 * Licensed under the MIT License 5 */ 6 7 /** 8 * @language=en 9 * <iframe src='../../../examples/WebSound.html?noHeader' width = '320' height = '310' scrolling='no'></iframe> 10 * <br/> 11 * demo: 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 Audio playing manager. 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=en 35 * Activate audio function. Note: Require user action events to activate. Currently support WebAudio. 36 */ 37 enableAudio: function(){ 38 if(WebAudio.isSupported){ 39 WebAudio.enable(); 40 } 41 }, 42 43 /** 44 * @language=en 45 * Get audio element. Use WebAudio if supported. 46 * @param {String|Object} source If String, it's the source of the audio; If Object, it should contains a src property. 47 * @returns {WebAudio|HTMLAudio} Audio playing instance. 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=en 66 * Remove audio element. 67 * @param {String|Object} source If String, it's the source of the audio; If Object, it should contains a src property. 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=en 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 };