i'm trying to play an audio and get fadeIn and FadeOut volume when user click into respective buttons. This is my code:
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);
}
}
But things are not working out the way I would like. The music plays normally but fadeOut and fadeIn effects are disastrous: On click into "fadeIn button" then music plays and on Click into "fadeOut" button (two times?) the fadeOut is executed wrongly.
I would like it to work as well as this example:example fiddle link. But i'm don't need fade scroll function like showed in above example. I need fadeOut and fadeIn audio when user click into buttons.
Can anyone help me fadeOut and fadeIn the music correctly? Here is a example jsFiddle.