延迟50ms或100ms播放声音的最佳方法是什么? 这是我试过的东西:
var beat = new Audio('/sound/BEAT.wav');
var time = 300;
playbeats();
function playbeats(){
beat.cloneNode().play();
setTimeout(playbeats, time);
}
这是正常的,但我的目标是每100毫秒后播放BEAT.wav。当我将“time”变量更改为100时,它就是“滞后” 721ms是我的BEAT.wav(这就是为什么我使用cloneNode())
有什么方法可以解决这个问题?
答案 0 :(得分:1)
你可以使用setInterval(),参数是相同的。
setInterval(function() {
playbeats();
}, 100);
你的函数playbeats函数应该是。
function playbeats(){
var tempBeat=beat.cloneNode();
tempBeat.play();
}
你的整个程序应该是这样的。
var beat = new Audio('/sound/BEAT.wav');
setInterval(function() {
playbeats();
}, 100);
function playbeats(){
var tempBeat=beat.cloneNode();
tempBeat.play();
}
答案 1 :(得分:0)
您可以使用Web Audio API,但代码会有所不同。如果您想要Web Audio API的时序和循环功能,则需要先将文件加载到缓冲区中。它还要求您的代码在服务器上运行。这是一个例子:
var audioContext = new AudioContext();
var audioBuffer;
var getSound = new XMLHttpRequest();
getSound.open("get", "sound/BEAT.wav", true);
getSound.responseType = "arraybuffer";
getSound.onload = function() {
audioContext.decodeAudioData(getSound.response, function(buffer) {
audioBuffer = buffer;
});
};
getSound.send();
function playback() {
var playSound = audioContext.createBufferSource();
playSound.buffer = audioBuffer;
playSound.loop = true;
playSound.connect(audioContext.destination);
playSound.start(audioContext.currentTime, 0, 0.3);
}
window.addEventListener("mousedown", playback);
答案 2 :(得分:0)
我还建议使用Web Audio API。从那里,您可以简单地每100毫秒或50毫秒或任何您想要的时间循环缓冲源节点。 为此,如其他响应中所述,您需要使用XMLHttpRequest通过服务器加载声音文件
// set up the Web Audio context
var audioCtx = new AudioContext();
// create a new buffer
// 2 channels, 4410 samples (100 ms at 44100 samples/sec), 44100 samples per sec
var buffer = audioCtx.createBuffer(2, 4410, 44100);
// load the sound file via an XMLHttpRequest from a server
var request = new XMLHttpRequest();
request.open('GET', '/sound/BEAT.wav', true);
request.responseType = 'arraybuffer';
request.onload = function () {
var audioData = request.response;
audioCtx.decodeAudioData(audioData, function (newBuffer) {
buffer = newBuffer;
});
}
request.send();
现在您可以使缓冲区源节点循环播放
// create the buffer source
var bufferSource = audioCtx.createBufferSource();
// set the buffer we want to use
bufferSource.buffer = buffer;
// set the buffer source node to loop
bufferSource.loop = true;
// specify the loop points in seconds (0.1s = 100ms)
// this is a little redundant since we already set our buffer to be 100ms
// so by default it would loop when the buffer comes to an end (at 100ms)
bufferSource.loopStart = 0;
bufferSource.loopEnd = 0.1;
// connect the buffer source to the Web Audio sound output
bufferSource.connect(audioCtx.destination);
// play!
bufferSource.start();
请注意,如果您通过bufferSource.stop()
停止播放,则无法再次启动。您只能拨打start()
一次,因此如果您想再次开始播放,则需要创建新的源节点。
请注意,由于声音文件通过XMLHttpRequest
加载的方式,如果您尝试在不运行服务器的情况下在计算机上对此进行测试,则在大多数浏览器上都会出现交叉引用请求错误。因此,如果要在计算机上测试它,最简单的解决方法是运行Python SimpleHTTPServer