【问题标题】:jQuery: fadeIn and fadeOut html audio with setInterval()jQuery:使用 setInterval() 淡入和淡出 html 音频
【发布时间】:2021-06-13 20:40:11
【问题描述】:

当用户单击相应的按钮时,我正在尝试播放音频并获得淡入和淡出音量。这是我的代码:

HTML:


<div class="rain-play">
Click to fadeIn sound
</div>

<div class="rain-pause">
Click to fadeOut Sound
</div>

<audio id="dv-rain" preload="auto">
    <source src="http://peterewendy.com.br/Genero/Mp3/ROCK/ACDC_-_Back_In_Black_-_P&W.mp3" type="audio/mpeg" />
</audio>

CSS:

.rain-play {
  display: block;
  background-color: #000;
  color: #fff;
  margin: 2vh;
  padding: 2vh;
  cursor: pointer;
  font-size: calc(14px + 0.5vw);
}

.rain-pause {
  display: block;
  background-color: #000;
  color: #fff;
  margin: 2vh;
  padding: 2vh;
  cursor: pointer;
  font-size: calc(14px + 0.5vw);
}

javascript:

  /* control interval variables */
  var pauseInterval;
  var playInterval;
  
 /* audio variable */
  var audio = $('#dv-rain').get(0);
  

/* Play on Click */
$('.rain-play').unbind().click(function() {
    playInterval = setInterval(fadeInSound, 10); 
    audio.play();
});
/* fadeOut on Click */
$('.rain-pause').unbind().click(function() {
  var pauseInterval = setInterval(fadeOutSound, 10);

});

/* fadeIn function */
function fadeInSound() {
  var volumeControl =  Math.min(audio.volume + 0.01, 1);
  if (volumeControl <= 1.0) {
      audio.volume = volumeControl;
      volumeControl++;
       console.log(volumeControl);
  } else {
    clearInterval(playInterval);
    clearInterval(pauseInterval);
  }
}
/* fadeOut function */
function fadeOutSound() {
  var volumeControl =  Math.min(audio.volume - 0.01, 1);
  if ((volumeControl >= 0.0) && (volumeControl <= 1.0))   {
      audio.volume = volumeControl;
      volumeControl--;
      console.log(volumeControl);
  } else {
    clearInterval(playInterval);
    clearInterval(pauseInterval);
  }
}

但事情并没有按照我想要的方式进行。音乐播放正常,但fadeOut 和fadeIn 效果是灾难性的:点击“fadeIn 按钮”然后播放音乐,点击“fadeOut”按钮(两次?)fadeOut 执行错误。

我希望它和这个例子一样工作:example fiddle link。但我不需要像上面示例中所示的淡入淡出滚动功能。当用户点击按钮时,我需要淡出和淡入音频。

谁能帮我正确淡出和淡入音乐?这是一个例子jsFiddle

【问题讨论】:

  • 这个能回答你的问题吗? stackoverflow.com/questions/7451508/…
  • @raddevus 不幸的是没有。使用此代码,我收到:“$audio 未定义”。我正在使用 jquery 2.2.4。
  • 从 'audio' 变量中删除 '$' 并单击按钮没有任何反应。
  • 感谢@raddevus,您的回答帮助我解决了问题。更改了“ var audio = $('#dv-rain').get(0);”到“var audio = $('#dv-rain');”

标签: javascript


【解决方案1】:

完整的解决方案:

$(document).ready(function(){
  var audio = $('#dv-rain');
  $('.rain-play').click(function() {
    audio.animate({volume: 1}, 1000, 'swing', function() {
        audio[0].play();
      });
  });
  $('.rain-pause').click(function() {
      audio.animate({volume: 0}, 1000, 'swing', function() {
        // really stop music
        audio[0].pause();
      })
  });
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-07
    • 2015-08-04
    • 1970-01-01
    • 2015-10-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多