How to Stop All Background Sound on Page Change - MrElbow
El mejor sitio con información útil para tu vida. Artículos acerca de felicidad, productividad, dinero, estilo de vida y mucho más. Sugiérenos un tema y escribiremos al respecto.
post-template-default,single,single-post,postid-15662,single-format-standard,ajax_fade,page_not_loaded,,qode-theme-ver-7.4,wpb-js-composer js-comp-ver-4.5.2,vc_responsive

How to Stop All Background Sound on Page Change


16 Jul How to Stop All Background Sound on Page Change

Internet Explorer 9, 10 and 11 have a problem using bgsound. When the user clicks the play button, the last audio reproduced was reproduced again when the user changes the page (well, at least that happened in my AngularJS application).

I tried several ways to stop the bgsound and at the end I found the way to solve it. I just removed the src property from all the bgsound elements in the page.


How to Stop the Background Sound in my Angular Application

The key part here is to find the right moment to remove the src property from the bgsound elements. I think that the best moment to do it is during the change page (route) event.

AngularJS have an event called $routeChangeStarted that is broadcasted before the route change, this will work to solve your problem if you are using the route mechanism in your application. To know more about this event, you can read the $route documentation.

What you can do in Angular is to listen when the $routeChangeStart event is triggered and get all the bgsound elements. After getting all the elements, you can clear the src property one by one. Here is a sample code to do that:

$scope.$on('$routeChangeStart', function(next, current) {
   var bgsoundElems = document.getElementsByTagName('bgsound');
   for(var i = 0; i < bgsoundElems.length; i++){
      bgsoundElems[i].src = '';


If you are using ui-router, there is an event called $stateChangeStart, that is similar to the $routeChangeStart event. For more information about the ui-router events, you can read the ui-router wiki.


Why Did I Use Deprecated bgsound?

I decided to use bgsound because our application needed to play WAV files in Internet Explorer. Since the audio tag does not support WAV files in Internet Explorer we had to create a new solution using a combination of the audio and bgsound (deprecated) tags.

This approach worked in other browsers such as Google Chrome.


If you want to read more of my technical articles, click here.

Follow me on Twitter.

No Hay Comentarios

Publicar Un Comentario