I have an audio element
var audioSrc = 'https://mfbx9da4.github.io/assets/audio/dope-drum-loop_C_major.wav'
var audio = document.createElement('audio')
audio.src = audioSrc
I need the AudioBuffer
to do beat detection so I tried accessing the buffer when the audio is loaded as so:
audio.oncanplaythrough = () => {
console.info('loaded');
var source = context.createMediaElementSource(audio);
source.connect(context.destination);
console.info('source.buffer', source.buffer);
source.start()
}
However, the above code snippet logs
> loaded
> source.buffer undefined
It seems the best way to do this is to avoid <audio>
tags and load the audio via XHR:
var context = new (window.AudioContext || window.webkitAudioContext)();
var audioSrc = 'https://mfbx9da4.github.io/assets/audio/dope-drum-loop_C_major.wav'
fetch(audioSrc, onSuccess)
function fetch (url, resolve) {
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.responseType = 'arraybuffer';
request.onload = function () { resolve(request) }
request.send()
}
function onSuccess (request) {
var audioData = request.response;
context.decodeAudioData(audioData, onBuffer, onDecodeBufferError)
}
function onBuffer (buffer) {
var source = context.createBufferSource();
console.info('Got the buffer', buffer);
source.buffer = buffer;
source.connect(context.destination);
source.loop = true;
source.start()
}
function onDecodeBufferError (e) {
console.log('Error decoding buffer: ' + e.message);
console.log(e);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.