2017-07-06 55 views
1

我想淡入一个MP3的音量到1如果身体有类fp-viewing-0 如何这不工作和音量doesn不会改变我该如何解决这个问题?如果人体有类似的淡入淡出的MP3声音其他淡出

代码:

var audio0 = document.getElementById('audio-0'); 
audio0.volume = 0; 

setInterval(function(){ 
      if ($("body").hasClass("fp-viewing-0")) { 
      audio0.animate({volume: 1}, 1000); 
      } 

else { 
    audio0.animate({volume: 0}, 1000); 
      } 

}, 100); 

HTML

<audio id="audio-0" src="1.mp3" autoplay="autoplay"></audio> 

我也试过:

$("#audio-0").prop("volume", 0); 


setInterval(function(){ 
      if ($("body").hasClass("fp-viewing-0")) { 
      $("#audio-0").animate({volume: 1}, 3000); 
      } 

else { 
    $("#audio-0").animate({volume: 0}, 3000); 
      } 

}, 100); 

亲切的问候!

回答

1

我已经将jquery动画部分更改为手工制作的淡入淡出效果。为此,我创建了淡入淡出时间和步骤数来操纵淡入淡出效果。

var audio0 = document.getElementById('audio-0'); 
audio0.volume = 0; 

if ($("body").hasClass("fp-viewing-0")) { 
    audio0.volume = 1; //max volume 
    var fadeTime = 1500; //in milliseconds 
    var steps = 150; //increasing makes the fade smoother 
    var stepTime = fadeTime/steps; 
    var audioDecrement = audio0.volume/steps; 

    var timer = setInterval(function(){ 
     audio0.volume -= audioDecrement; //fading out 

     if (audio0.volume <= 0.03){ //if its already inaudible stop it 
       audio0.volume = 0; 
       clearInterval(timer); //clearing the timer so that it doesn't keep getting called 
     } 
    }, stepTime); 
} 
更好

将是把所有这一切在相应的接收这些值的淡入淡出功能,使其逐步开展:

function fadeAudio(audio, fadeTime, steps){ 
    audio.volume = 1; //max 
    steps = steps || 150; //turning steps into an optional parameter that defaults to 150 
    var stepTime = fadeTime/steps; 
    var audioDecrement = audio.volume/steps; 

    var timer = setInterval(function(){ 
     audio.volume -= audioDecrement; 

     if (audio.volume <= 0.03){ //if its already inaudible stop it 
      audio.volume = 0; 
      clearInterval(timer); 
     } 
    }, stepTime); 
} 

这将使你的代码有很多更紧凑和可读性:

var audio0 = document.getElementById('audio-0'); 
audio0.volume = 0; 
if ($("body").hasClass("fp-viewing-0")) { 
    fadeAudio(audio0, 1500); 
} 
+0

谢谢!如果if条件会使音频淡入淡出,那么我会如何处理else语句,以便我可以将其他条件放在其他条件中以使音频淡出? –

+0

@Neths我不确定我了解你的问题。如果在'body'中有'fp-viewing-0'类,最后一个块中的这个'if'将会淡化音频,否则它不会执行任何操作。它也有'volume = 0'。所以最终的结果是,如果课堂存在,它会使音频淡化,否则你听不到任何声音。如果你删除上面的'audio0.volume = 0',那么如果类存在,它会消失,否则它会保持音频播放。 – Isac