bgm.start();
var bgm = {
typedef : ['ji','niu','yang','niao'],
buffer : {},
context : null,
timeout : 3000,
start: function(){
this.cacheBuf();
this.run();
},
run: function(){
setTimeout(function(){
if(this.context != null){
this.context.close();
this.context = null;
}
var _li = Math.floor((Math.random()*this.typedef.length));
this.audioPlay(this.typedef[_li]);
this.run();
}, this.timeout);
},
audioPlay: function(tp){
var _this = this;
var _buff = this.buffer[tp].slice(0, this.buffer[tp].byteLength);
this.context = new (window.AudioContext || window.webkitAudioContext)();
this.context.decodeAudioData(_buff, function(buffer){
var source = _this.context.createBufferSource();
source.buffer = buffer;
source.connect(_this.context.destination);
source.start(0);
});
},
cacheBuf: function(){for(i in this.typedef){
_tp = this.typedef[i];
this.getbuf('static/audio/'+ _tp +'.mp3', _tp);
}
},
getbuf: function(url, tp){
var _this = this;
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'arraybuffer';
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
_this.buffer[tp] = xhr.response;
}
};
xhr.send();
}
};