Skip to content

Commit

Permalink
feat: auto cache WebAudio buffer & add WebAudio.clearBufferCache
Browse files Browse the repository at this point in the history
  • Loading branch information
06wj committed Jun 23, 2016
1 parent fb384ba commit 79203d7
Showing 1 changed file with 43 additions and 34 deletions.
77 changes: 43 additions & 34 deletions src/media/WebAudio.js
Original file line number Diff line number Diff line change
Expand Up @@ -96,25 +96,26 @@ return Class.create(/** @lends WebAudio.prototype */{
*/
load: function(){
if(!this._buffer){
var request = new XMLHttpRequest();
request.src = this.src;
request.open('GET', this.src, true);
request.responseType = 'arraybuffer';
request.onload = this._onAudioEvent;
request.onprogress = this._onAudioEvent;
request.onerror = this._onAudioEvent;
request.send();
var buffer = WebAudio._bufferCache[this.src];
if(buffer){
this._onDecodeComplete(buffer);
}
else{
var request = new XMLHttpRequest();
request.src = this.src;
request.open('GET', this.src, true);
request.responseType = 'arraybuffer';
request.onload = this._onAudioEvent;
request.onprogress = this._onAudioEvent;
request.onerror = this._onAudioEvent;
request.send();
}
this._buffer = true;
}
return this;
},

/**
* @language=en
* @private
*/
/**
* @language=zh
* @private
*/
_onAudioEvent: function(e){
Expand Down Expand Up @@ -143,40 +144,29 @@ return Class.create(/** @lends WebAudio.prototype */{
},

/**
* @language=en
* @private
*/
/**
* @language=zh
* @private
*/
_onDecodeComplete: function(audioBuffer){
if(!WebAudio._bufferCache[this.src]){
WebAudio._bufferCache[this.src] = audioBuffer;
}

this._buffer = audioBuffer;
this.loaded = true;
this.duration = audioBuffer.duration;
// console.log('onDecodeComplete:', audioBuffer.duration);

this.fire('load');
if(this.autoPlay) this._doPlay();
},

/**
* @language=en
* @private
*/
/**
* @language=zh
* @private
*/
_onDecodeError: function(){
this.fire('error');
},

/**
* @language=en
* @private
*/
/**
* @language=zh
* @private
*/
_doPlay: function(){
Expand All @@ -202,11 +192,6 @@ return Class.create(/** @lends WebAudio.prototype */{
},

/**
* @language=en
* @private
*/
/**
* @language=zh
* @private
*/
_clearAudioNode: function(){
Expand Down Expand Up @@ -361,6 +346,30 @@ return Class.create(/** @lends WebAudio.prototype */{
return true;
}
return this.enabled;
},
/**
* The audio buffer caches.
* @private
* @type {Object}
*/
_bufferCache:{},
/**
* @language=en
* Clear the audio buffer cache.
* @param {String} url audio's url. if url is none, it will clear all buffer.
*/
/**
* @language=zh
* 清除audio buffer 缓存。
* @param {String} url audio的网址,默认清除所有的缓存
*/
clearBufferCache:function(url){
if(url){
this._bufferCache[url] = null;
}
else{
this._bufferCache = {};
}
}
}
});
Expand Down

0 comments on commit 79203d7

Please sign in to comment.