1

Context

I have HTML audio playing in the background on my webpage that has a fade out/ fade in function that uses the jQuery .animate function to set the volume to 0 when fading out and sets it to 1 when fading in.

I have implemented the page visibility API: https://developer.mozilla.org/en-US/docs/Web/Guide/User_experience/Using_the_Page_Visibility_API

This is used to detect if the user switches tabs.

Currently I have the fade out function being called on the audio when the tab goes from visible to hidden and the fade in function being called when going from hidden to visible:

fadeOut(id){
   $(id).animate({volume: 0}, 1000});
}
fadeIn(id){
   $(id).animate({volume: 1}, 1000});
}

Problem

When switching tabs, going from visible to hidden, the fadeOut function is called however rather than going from volume 1 to 0 slowly, it goes straight to 0 after 1 second, but when it goes from hidden to visible it performs as expected, going from 0 to 1 slowly. I have tried switching the functions around and it seems that it only occurs when going from visible to hidden. It this an implementaion feature of the jQuery .animate function? Or am I missing something?

Console log output for each step

when going from hidden to visible:

"step time: " 0 " vol: " 0

"step time: " 42 " vol: " 0

"step time: " 44 " vol: " 0.025049273427930594

"step time: " 51 " vol: " 0.026579017009366445

"step time: " 60 " vol: " 0.030591727271815305

...

"step time: " 1000 " vol: " 1

going from visible to hidden

"step time: " 1000 " vol: " 1

"step time: " 0 " vol: " 0

Tom
  • 330
  • 1
  • 3
  • 17
  • I am not sure due to hav'nt worked with audio element but this may be because you hide or remove it when switching tabs? Post a fiddle of your tabs so we can easier debug – Erik Svedin Aug 21 '14 at 15:18

2 Answers2

3

I have found out that it is an optimization issue that the '.animate' function performs. When the page is 'hidden' - you're viewing another tab - jQuery will skip the animation steps because the viewer cannot actually see the animation. This is great for an actual animation but in this case when using sound, it jumps straight from 1 down to 0 skipping the steps in between.

I cannot find this mentioned in the API which is slightly annoying.

My current solution is to create my own 'animation' function to step down the level of sound in a recursive setTimeout loop.

Tom
  • 330
  • 1
  • 3
  • 17
0

something like this?

$(id).animate({volume: 0}, 1000);

From this post. html5-audio-playback-with-fade-in-and-fade-out

Community
  • 1
  • 1