Hilo/docs/api-zh/code/media/WebSound.js
2017-06-29 14:48:45 +08:00

91 lines
2.5 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* Hilo
* Copyright 2015 alibaba.com
* Licensed under the MIT License
*/
/**
* <iframe src='../../../examples/WebSound.html?noHeader' width = '320' height = '310' scrolling='no'></iframe>
* <br/>
* 使用示例:
* <pre>
* var audio = WebSound.getAudio({
* src: 'test.mp3',
* loop: false,
* volume: 1
* }).on('load', function(e){
* console.log('load');
* }).on('end', function(e){
* console.log('end');
* }).play();
* </pre>
* @class 声音播放管理器。
* @static
* @module hilo/media/WebSound
* @requires hilo/media/HTMLAudio
* @requires hilo/media/WebAudio
* @requires hilo/util/util
*/
var WebSound = {
_audios: {},
/**
* 激活音频功能。注意需用户事件触发此方法才有效。目前仅对WebAudio有效。
*/
enableAudio: function(){
if(WebAudio.isSupported){
WebAudio.enable();
}
},
/**
* 获取音频对象。默认优先使用 WebAudio
* @param {String|Object} source 若source为String则为音频src地址若为Object则需包含src属性。
* @param {Boolean} [preferWebAudio=true] 是否优先使用WebAudio默认 true 。
* @returns {WebAudio|HTMLAudio} 音频播放对象实例。
*/
getAudio: function(source, preferWebAudio){
if(preferWebAudio === undefined){
preferWebAudio = true;
}
source = this._normalizeSource(source);
var audio = this._audios[source.src];
if(!audio){
if(preferWebAudio && WebAudio.isSupported){
audio = new WebAudio(source);
}else if(HTMLAudio.isSupported){
audio = new HTMLAudio(source);
}
this._audios[source.src] = audio;
}
return audio;
},
/**
* 删除音频对象。
* @param {String|Object} source 若source为String则为音频src地址若为Object则需包含src属性。
*/
removeAudio: function(source){
var src = typeof source === 'string' ? source : source.src;
var audio = this._audios[src];
if(audio){
audio.stop();
audio.off();
this._audios[src] = null;
delete this._audios[src];
}
},
/**
* @private
*/
_normalizeSource: function(source){
var result = {};
if(typeof source === 'string') result = {src:source};
else util.copy(result, source);
return result;
}
};