Html5 <Audio> Playback with Fade in and Fade Out

HTML5 audio playback with fade in and fade out

The jQuery way...

$audio.animate({volume: newVolume}, 1000);

Edit: where $audio is a jQuery-wrapped audio element and newVolume is a double between 0 and 1.

Edit: The element's effective media volume is volume, interpreted relative to the range 0.0 to 1.0, with 0.0 being silent, and 1.0 being the loudest setting, values in between increasing in loudness. The range need not be linear. http://www.w3.org/html/wg/drafts/html/master/embedded-content.html#effective-media-volume

Edit: People are posting vanilla JavaScript implementations, so I'll post a vanilla TypeScript one that preserves the jQuery swing animation (just strip out the type info if you want to run this in JavaScript). Disclaimer, this is completely untested:

export async function adjustVolume(
element: HTMLMediaElement,
newVolume: number,
{
duration = 1000,
easing = swing,
interval = 13,
}: {
duration?: number,
easing?: typeof swing,
interval?: number,
} = {},
): Promise<void> {
const originalVolume = element.volume;
const delta = newVolume - originalVolume;

if (!delta || !duration || !easing || !interval) {
element.volume = newVolume;
return Promise.resolve();
}

const ticks = Math.floor(duration / interval);
let tick = 1;

return new Promise(resolve => {
const timer = setInterval(() => {
element.volume = originalVolume + (
easing(tick / ticks) * delta
);

if (++tick === ticks + 1) {
clearInterval(timer);
resolve();
}
}, interval);
});
}

export function swing(p: number) {
return 0.5 - Math.cos(p * Math.PI) / 2;
}

how to have fade in/out on audio HTML5

You have to watch out for the difference between the HTMLAudioElement ($('#musicBeat')[0]) and the jQuery Object ($('#musicBeat')).

play is a method of the HTMLAudioElement, so you'll have to access it over that (as you did), but .animate is a jQuery method and can only be called on a jQuery object.

And you have to specify newVolume (can't leave it empty).

var beepTwo = $("#musicBeat");
beepTwo[0].play();

$("#dan").click(function() {
if (beepTwo[0].paused == false) {
beepTwo.animate({volume: 0}, 2000, 'swing', function() {
// really stop the music
beepTwo[0].pause();
});
} else {
beepTwo[0].play();
beepTwo.animate({volume: 1}, 2000);
}
});

Trying to fadein/fadeout html5 audio file vuejs / vanilla js

I managed to get it working:

HTML

<audio
ref="audio"
src="@/assets/audio/bg-music.ogg"
preload
loop
id="audio"
muted
></audio>
<div
@click="toggleSound()"
class="toggle-sound"
v-bind:class="this.state.backgroundAudioState"
></div>

JS

data: () => ({
...
state: {
backgroundAudioState: "paused",
},
}),
methods: {
toggleSound() {
let backgroundAudio = this.$refs.audio;
let actualVolumeFadeOut = backgroundAudio.volume;
let actualVolumeFadeIn = 0;

//Fade In
if (this.state.backgroundAudioState === "paused") {
console.log("fading in");
this.state.backgroundAudioState = "playing";
clearInterval(fadeInInterval);
let fadeInInterval = setInterval(function() {
actualVolumeFadeIn = (parseFloat(actualVolumeFadeIn) + 0.1).toFixed(1);
if (actualVolumeFadeIn <= 1) {
backgroundAudio.volume = actualVolumeFadeIn;
} else {
backgroundAudio.play();
}
}, 100);
return false;
}

//Fade Out
if (this.state.backgroundAudioState === "playing") {
console.log("fading out");
this.state.backgroundAudioState = "paused";

let fadeOutInterval = setInterval(function() {
actualVolumeFadeOut = (parseFloat(actualVolumeFadeOut) - 0.1).toFixed(1);
if (actualVolumeFadeOut >= 0) {
backgroundAudio.volume = actualVolumeFadeOut;
} else {
backgroundAudio.pause();
clearInterval(fadeOutInterval);
}
}, 100);
return false;
}
},
}

jQuery: fadeIn and fadeOut html audio with setInterval()

Complete solution:

$(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();
})
});
})

Fade out of a Mp3 song using javascript

A couple things seem to need addressing ;)

First off, in the example you provided, you have not closed the audio tag.

Second, you are only setting a global vol var and not the volume of the audio object itself.

What you could try is keeping things scoped to the function and use the actual audio object volume rather than a 'global' vol var:

<script>
function aud_play() {
var myAudio = document.getElementById("myAudio");
myAudio.play();
}

function aud_fade(){
var timer,
myAudio = document.getElementById("myAudio");
if (myAudio.volume > 0) {
myAudio.volume -= 0.005;
timer = setTimeout(aud_fade,5);
}
}
</script>

<audio id="myAudio">
<source src="1.mp3" type='audio/mp4'>
</audio>
<button type="button" onclick="aud_play()">Play</button>
<button type="button" onclick="aud_fade()">Fade</button>

I have also adjusted the timeout and the volume amount to decrease, as volume is from 0 to 1. Reducing by 0.2 (20 percent) every 2 thousands of a second would 'fade out' in 0.1 of a second!

Here is the above in a Fiddle.

You may want to consider resetting the audio currentTime and volume when the fade completes or when you click play again (Note: There is no stop method, so pause and currentTime can achieve the same thing):

<script>

var fadeTimer = false;

var aud_play = function() {
clearTimeout(fadeTimer);
var myAudio = document.getElementById("myAudio");
myAudio.volume = 1;
myAudio.currentTime = 0;
myAudio.play();
}

var aud_fade = function() {
var myAudio = document.getElementById("myAudio");
if (myAudio.volume > 0.005) {
myAudio.volume -= 0.005;
fadeTimer = setTimeout(aud_fade,5);
} else {
myAudio.volume = 0;
myAudio.pause();
myAudio.currentTime = 0;
}
}
</script>

<audio id="myAudio">
<source src="1.mp3" type='audio/mp4'>
</audio>
<button type="button" onclick="aud_play()">Play</button>
<button type="button" onclick="aud_fade()">Fade</button>

Here is the above example in another Fiddle.

Hope this helps!

EDIT:

Regarding Fade In, you could replicate the 'aud_fade' method but increase volume when less than 1 rather than decrease when greater than 0, than call the fade in method on the start method:

var aud_play = function() {
clearTimeout(fadeTimer);
var myAudio = document.getElementById("myAudio");
myAudio.volume = 0; // 0 not 1, so we can fade in
myAudio.currentTime = 0; // set mp3 play positon to the begining
myAudio.play(); // start mp3
aud_fade_in(); // call fade in method
};

var aud_fade_in = function() {
clearTimeout(fadeTimer);
var myAudio = document.getElementById("myAudio");
if (myAudio.volume < 9.995) {
myAudio.volume += 0.005;
fadeTimer = setTimeout(aud_fade_in,10);
} else {
myAudio.volume = 1;
}
};

var aud_fade_out = function() {
clearTimeout(fadeTimer);
var myAudio = document.getElementById("myAudio");
if (myAudio.volume > 0.005) {
myAudio.volume -= 0.005;
fadeTimer = setTimeout(aud_fade_out,5);
} else {
myAudio.volume = 0;
myAudio.pause();
myAudio.currentTime = 0;
}
};

Here is the above in a Fiddle.

Fade in/out all html5 audio on section.active with fullpage.js

No need to get into fullpage.js code to do it. In fact, you shouldn't if you want to keep updating to the latest fullPage.js version and so on.

You can remove the automatic play and pause and do it yourself by using fullpage.js callbacks.

To mute them you could do something like this:

$('#fullpage').fullpage({
anchors: ['firstPage', 'secondPage', 'thirdPage', 'fourthPage', 'lastPage'],

onLeave: function(index, nextIndex, direction){
var leavingSection = $(this);

leavingSection.find('audio, body video').each(function() {
$(this).animate({volume: 0}, 1000, function () {
muted = true;
});
});
}
});

How to apply a fade effect in HTML5 mute button

The audio object should be a JQuery-object in order to use the JQuery .animate() function. You can do that by changing audio.animate to $(audio).animate.

Also the audio.muted = ... statements turn off/on the music instantly, so you won't hear the animations.

A working example:

audio = new Audio();audio.src = "http://myst729.qiniudn.com/within-temptation_pale.mp3"audio.play();
$(".mute").on("click tap", function() { var $btn = $(this); var muted = audio.muted; if (muted) audio.muted = false; // It cannot be animated if it's muted $btn.prop('disabled', true); // Optional $(audio).animate({volume: muted ? 1 : 0}, 2000, function() { audio.muted = !muted; $btn.text(muted ? "mute" : "unmute"); $btn.prop('disabled', false); // Optional });});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><button class="mute">mute</button>


Related Topics



Leave a reply



Submit