我正在尝试使用给定的 HTMLAudio 元素制作淡入/淡出效果。 为此,为了使用 Web Audio API 的 AudioParam 接口(interface),我将 HTMLAudio 元素包裹在一个 MediaElementSource 节点周围,并将其连接到一个 Gain 节点。 以下代码在桌面 Chrome 浏览器中完美运行。 但是,它不适用于 Android Chrome。 (声音并没有减弱,而是在 2 秒后突然停止。)
<!DOCTYPE html>
<body>
<button disabled>Play</button>
<script>
var button = document.getElementsByTagName('button')[0];
var audioElem = new Audio();
audioElem.src = 'bgm.mp3';
var ctx = new AudioContext();
var sourceNode = ctx.createMediaElementSource(audioElem);
var gainNode = ctx.createGain();
sourceNode.connect(gainNode);
gainNode.connect(ctx.destination);
audioElem.addEventListener('canplay', function () {
button.disabled = false;
}, false);
button.addEventListener('click', function () {
if (button.textContent === 'Play') {
// Fade in
audioElem.play();
fade(0, 1, 2)
.then(function () {
button.textContent = 'Pause';
button.disabled = false;
});
} else {
// Fade out
fade(1, 0, 2)
.then(function () {
audioElem.pause();
button.textContent = 'Play';
button.disabled = false;
});
}
button.disabled = true;
}, false);
function fade(start, end, duration) {
return new Promise(function (pFulfill, pReject) {
// Fade in/out using AudioParam interface.
gainNode.gain.linearRampToValueAtTime(start, ctx.currentTime);
gainNode.gain.linearRampToValueAtTime(end, ctx.currentTime + duration);
setTimeout(function () {
pFulfill();
}, duration * 1000);
});
}
</script>
</body>
有人知道解决方法吗?
最佳答案
这是 Android Chrome 中的一个已知错误:https://code.google.com/p/chromium/issues/detail?id=240415 .
关于android - 无法在 Android Chrome 中使用 MediaElementSource 和 AudioParam 接口(interface)淡入/淡出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25658318/