[英]Mute/Unmute video's Audio progressively
使用此代码,我可以切换静音/取消静音正在播放的视频的音频:
const btn = document.getElementById('mute'),
video = document.querySelector('video');
btn.addEventListener('click', () => {
if (btn.value === 'unmuted') {
btn.value = 'muted';
btn.innerHTML = '<i class="fas fa-volume-mute"></i>';
video.muted = true;
} else {
btn.value = 'unmuted';
btn.innerHTML = '<i class="fas fa-volume-up"></i>';
video.muted = false;
}
});
<a id="mute" value="muted"><i class="fas fa-volume-mute"></i></a>
单击按钮而不是立即静音/取消静音时,如何添加淡入/淡出音频效果?
谢谢。
您可以使用JQuery .animate淡入/淡出视频。 动画音量为双倍(0到1之间)
var $video_player = $('#video-player'); var $mute_button = $('#mute-button'); $mute_button.on('click', () => { $video_player.toggleClass('mute'); if ($video_player.hasClass('mute')) { // Fade out audio $video_player.animate({ volume: 0 }, 5000); $mute_button.html('unmute'); } else { // Fade in audio $video_player.animate({ volume: 1 }, 5000); $mute_button.html('mute'); } });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <video id="video-player" width="100%" height="150px" controls autoplay> <source src="http://grochtdreis.de/fuer-jsfiddle/video/sintel_trailer-480.mp4" type="video/mp4"> </video> <center><button id="mute-button">mute</button></center>
我看到您没有使用jQuery,因此这里有一个适合您的香草JavaScript解决方案。 仅为一种简单功能导入一个巨大的库是不切实际的。
没有任何库,实际上不难产生淡入淡出效果。 所有你需要的是:
您可以查看要点 ,以获取要使用的缓动功能列表。
对于下面的示例,我使用“ easeInOutCubic”:
const btn = document.getElementById('mute'),
video = document.querySelector('video');
btn.addEventListener('click', () => {
if (btn.value === 'unmuted') {
btn.value = 'muted';
btn.innerHTML = '<i class="fas fa-volume-mute"></i>';
muteVideo(true);
} else {
btn.value = 'unmuted';
btn.innerHTML = '<i class="fas fa-volume-up"></i>';
muteVideo(false);
}
});
function muteVideo(bool){
// Set fade speed.
// The lower the speed, the slower the fade.
const speed = 0.00025;
// Get video initial volume.
const i = video.volume;
// If true, fade out
// else, fade in
if (bool === true){
for (; i >= 0; i -= speed){
video.volume = easeInOutCubic(i);
}
} else {
for (; i <= 1; i += speed){
video.volume = easeInOutCubic(i);
}
}
}
// See https://gist.github.com/gre/1650294
function easeInOutCubic(t){
return t < 0.5
? 4*t*t*t
: (t - 1)*(2*t - 2)*(2*t - 2) + 1;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.