gpt4 book ai didi

html - Web Audio API:如何加载另一个音频文件?

转载 作者:行者123 更新时间:2023-12-03 00:19:43 25 4
gpt4 key购买 nike

我想为HTML5 Web Audio API编写一个基本脚本,可以播放一些音频文件。但是我不知道如何卸载正在播放的音频并加载另一个音频。在我的脚本中,两个音频文件正在同时播放,但不是我想要的。

这是我的代码:

var context, 
soundSource,
soundBuffer;

// Step 1 - Initialise the Audio Context
context = new webkitAudioContext();

// Step 2: Load our Sound using XHR
function playSound(url) {
// Note: this loads asynchronously
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.responseType = "arraybuffer";

// Our asynchronous callback
request.onload = function() {
var audioData = request.response;
audioGraph(audioData);
};

request.send();
}

// This is the code we are interested in
function audioGraph(audioData) {
// create a sound source
soundSource = context.createBufferSource();

// The Audio Context handles creating source buffers from raw binary
soundBuffer = context.createBuffer(audioData, true/* make mono */);

// Add the buffered data to our object
soundSource.buffer = soundBuffer;

// Plug the cable from one thing to the other
soundSource.connect(context.destination);

// Finally
soundSource.noteOn(context.currentTime);
}

// Stop all of sounds
function stopSounds(){
// How can do this?
}


// Events for audio buttons
document.querySelector('.pre').addEventListener('click',
function () {
stopSounds();
playSound('http://thelab.thingsinjars.com/web-audio-tutorial/hello.mp3');
}
);
document.querySelector('.next').addEventListener('click',
function() {
stopSounds();
playSound('http://thelab.thingsinjars.com/web-audio-tutorial/nokia.mp3');
}
);

最佳答案

您应该在启动时将声音预先加载到缓冲区一次,并在需要播放时简单地重置AudioBufferSourceNode

要依次播放多种声音,您需要根据缓冲区的长度,使用noteOn(time)依次安排它们。

要停止声音,请使用noteOff

听起来您似乎缺少一些基本的网络音频概念。对此进行了详细描述,并在HTML5Rocks tutorialFAQ中与样本一起显示。

关于html - Web Audio API:如何加载另一个音频文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11415555/

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