此代码可以正确吗?有什么好主意吗? “ this.http”是一个ajax lib对象,因此不必在意。 “ res”是从服务器请求的音频数据。
window['AudioContext'] = window['AudioContext'] || window['webkitAudioContext']
this.http.get(audio.sourceUrl, {
responseType: 'arraybuffer'
}).subscribe((res) => {
if (this.source) {
this.source.disconnect(0)
this.source.buffer = null
}
if (this.audioCtx) {
this.audioCtx.close()
}
this.audioCtx = new AudioContext()
this.audioCtx.decodeAudioData(res, (buffer) => {
this.source = this.audioCtx.createBufferSource() // creates a sound source
this.source.buffer = buffer // tell the source which sound to play
this.source.connect(this.audioCtx.destination) // connect the source to the context's destination (the speakers)
this.source.start(0)
}, this.onError)
})
我见过这样的人的代码,但我不知道他为什么这样尝试:
var ctx = new AudioContext(),
scratchBuffer = ctx.createBuffer(1, 1, 22050);
class WebAudioAdapter extends AudioAdapter {
close() {
if( this.__src ) {
this.__src.onended = null;
this.__src.disconnect(0);
try { this.__src.buffer = scratchBuffer; } catch(e) {}
this.__src = null;
}
}
}