我尝试使用给定的HTMLAudio元素制作淡入/淡出效果。 为此目的使用Web Audio API的AudioParam接口,我将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>
有没有人知道任何变通办法?
答案 0 :(得分:3)
这是Android Chrome中的已知错误:https://code.google.com/p/chromium/issues/detail?id=240415。
答案 1 :(得分:0)
值得一提的是,您可以设置视频元素的音量,如:
$('video').volume = 0.5