gpt4 book ai didi

javascript - Web 音频 API 获取

转载 作者:数据小太阳 更新时间:2023-10-29 06:09:44 26 4
gpt4 key购买 nike

我有一个音频元素

var audioSrc = 'https://mfbx9da4.github.io/assets/audio/dope-drum-loop_C_major.wav'
var audio = document.createElement('audio')
audio.src = audioSrc

我需要 AudioBufferbeat detection所以我尝试在加载音频时访问缓冲区:

audio.oncanplaythrough = () => {
console.info('loaded');
var source = context.createMediaElementSource(audio);
source.connect(context.destination);
console.info('source.buffer', source.buffer);
source.start()
}

但是,上面的代码片段日志

> loaded
> source.buffer undefined

最佳答案

似乎最好的方法是避免 <audio>标记并通过 XHR 加载音频:

const audioContext = new (window.AudioContext || window.webkitAudioContext)();
const audioSrc =
"https://davidalbertoadler.com/assets/audio/dope-drum-loop_C_major.wav";

const audioData = await fetchAudio(audioSrc);
audioContext.decodeAudioData(audioData, onDecoded, onDecodeError);

function fetchAudio(url) {
return new Promise((resolve, reject) => {
const request = new XMLHttpRequest();
request.open("GET", url, true);
request.responseType = "arraybuffer";
request.onload = () => resolve(request.response);
request.onerror = (e) => reject(e);
request.send();
});
}

function onDecoded(buffer) {
// Play the song
console.log("Got the decoded buffer now play the song", buffer);
const source = audioContext.createBufferSource();
source.buffer = buffer;
source.connect(audioContext.destination);
source.loop = true;
source.start();
}

function onDecodeError(e) {
console.log("Error decoding buffer: " + e.message);
console.log(e);
}

关于javascript - Web 音频 API 获取 <audio> 元素的 AudioBuffer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46856331/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com