gpt4 book ai didi

javascript - 淡出后淡入音频

转载 作者:行者123 更新时间:2023-12-01 01:49:42 25 4
gpt4 key购买 nike

在我的程序中,我的开始屏幕上有背景音乐。此功能是在单击开始按钮后淡出背景声音。

$(bgMusic).on('timeupdate', function () {
var vol = 1,
interval = 250;
if (bgMusic.volume == 1) {
var intervalID = setInterval(function () {
if (vol > 0) {
vol -= 0.05;
bgMusic.volume = vol.toFixed(2);
} else {
clearInterval(intervalID);
}
}, interval);
}
});

我现在添加了一个重新启动按钮,可以带您返回开始屏幕,因此我需要以相同的速度淡入音乐。我尝试了一些方法,但不起作用,有人可以帮助我吗?

我需要一些类似的东西:

$(bgMusic).off('timeupdate', function () {
var vol = 0,
interval = 250;
if (bgMusic.volume == 0) {
var intervalID = setInterval(function () {
if (vol < 0) {
vol += 0.05;
bgMusic.volume = vol.toFixed(2);
} else {
clearInterval(intervalID);
}
}, interval);
}
});

最佳答案

可能有更好的方法来做到这一点,但我只是写了一个音量推子来更习惯 <audio> .

要在您的 <audio> 上启用它通过enableFader(yourAudioNode) ,然后淡出调用 yourAudioNode.fadeOut() ,或淡入通话 yourAudioNode.fadeIn() .
它基于监听时间更新,因此除非您指定较慢的速率,否则它将以 explained here 的频率更改音量。 .

function enableFader(node, per_step, min_interval) {
'use strict';
var fadeOut, fadeIn;
node.fadeSettings = {
dir : 0,
step : per_step || 0.05,
interval : min_interval || 0.150,
lastTime : -Infinity
};
fadeOut = function fadeOut() {
var vol = this.volume,
settings = this.fadeSettings,
ctime = this.currentTime,
dtime = Math.abs(ctime - settings.lastTime);
if (settings.dir === -1 && dtime >= settings.interval && vol > 0) {
settings.lastTime = ctime;
this.volume = (vol - settings.step).toFixed(2);
} else if (vol <= 0 || settings.dir !== -1) {
this.removeEventListener('timeupdate', fadeOut);
settings.dir = 0;
}
};
fadeIn = function fadeIn() {
var vol = this.volume,
settings = this.fadeSettings,
ctime = this.currentTime,
dtime = Math.abs(ctime - settings.lastTime);
if (settings.dir === 1 && dtime >= settings.interval && vol < 1) {
settings.lastTime = ctime;
this.volume = (vol + settings.step).toFixed(2);
} else if (vol >= 1 || settings.dir !== 1) {
this.removeEventListener('timeupdate', fadeIn);
settings.dir = 0;
}
};
node.fadeOut = function () {
this.fadeSettings.dir = -1;
this.addEventListener('timeupdate', fadeOut, false);
};
node.fadeIn = function () {
this.fadeSettings.dir = 1;
this.addEventListener('timeupdate', fadeIn, false);
};
}

我在 this page 上测试过它在 Google Chrome 中使用我的开发控制台。

var a = document.getElementById('song');
enableFader(a);
a.fadeOut();
// a.fadeIn();

关于javascript - 淡出后淡入音频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13585381/

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