簡體   English   中英

逐漸將視頻的音頻靜音/取消靜音

[英]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解決方案。 僅為一種簡單功能導入一個巨大的庫是不切實際的。

沒有任何庫,實際上不難產生淡入淡出效果。 所有你需要的是:

  1. 循環或動畫幀
  2. 緩動功能。

您可以查看要點 ,以獲取要使用的緩動功能列表。

對於下面的示例,我使用“ 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM