如何为音频创建暂停功能?我已经在下面的脚本中有一个播放功能。
function loadSound(url) {
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.responseType = 'arraybuffer';
// When loaded decode the data
request.onload = function() {
// decode the data
context.decodeAudioData(request.response, function(buffer) {
// when the audio is decoded play the sound
playSound(buffer);
}, onError);
}
request.send();
}
function playSound(buffer) {
sourceNode.buffer = buffer;
sourceNode.noteOn(0);
}
但我怎么能暂停或停止呢?
答案 0 :(得分:12)
简短的回答是“你不能暂停它 - 你可以通过调用sourceNode.noteOff(0)来阻止它 - 正如idbehold所说的那样;”。
您无法暂停,原因与音频线上没有“暂停”按钮相同 - 因为数据一直在运行。您可以实现一个可以暂停的记录器节点,但是如果您不取消暂停,它会在某些时候缓冲大量数据。
实现此场景的常用方法是跟踪您在播放中的位置(例如,通过记住您何时开始),然后当您想要暂停时记住该偏移,请调用noteOff(0),然后何时你想重新开始播放创建一个指向同一个缓冲区的新节点,并用偏移调用noteOnGrain。
答案 1 :(得分:4)
noteOff(0)
的问题是它会破坏AudioNode
,因此您将无法使用暂停音频。相反,您可以直接断开sourceNode
,这将有效地暂停音频。要恢复播放,只需重新连接即可。由于您的代码将sourceNode
与analyser
连接起来:
function pause() {
sourceNode.disconnect();
}
function resume() {
sourceNode.connect(analyser);
}
希望有所帮助!
答案 2 :(得分:0)
在分配缓冲区之前,您已经创建了一个可以使用上下文的bufferSource。 创建bufferSource的方法是“createBufferSource”=> context.createBufferSource。在创建bufferSource之后,您使用“context.destination”=>创建了一个conexion。 source.connect(context.destination);.是现在玩,现在使用start(0)到现代浏览器,对于旧浏览器是noteOn(0)
function loadSound() {
xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'arraybuffer';
xhr.onload = function () {
/* Processing response data - xhr.response */
/* Decoding audio data. */
var context = new webkitAudioContext();
context.decodeAudioData(xhr.response, function onSuccess (buffer) {
if (! buffer) {
alert('Error decoding file data.');
return;
}
var source = context.createBufferSource(); /* Create SourceNode. */
source.buffer = buffer; /* buffer variable is data of AudioBuffer type from the decodeAudioData() function. */
source.connect(context.destination); /* Connect SourceNode to DestinationNode. */
source.start(0); /* Play sound. */
}, function onError (error) {
alert('Error decoding file data.');
});
};
xhr.onerror = function () {
/* Handling errors */
console.log('error');
};
xhr.send();
}