Search code examples
ruby-on-railsfirefoxhtml5-audioturbolinks

How do I stop HTML5 audio upon page refresh in Firefox


Within my Rails app, I have a view where, when you refresh the page, a new song plays.

When I manually refresh the page, the old song stops and a new song starts playing. But, in Firefox, when I click on a button inside the view to refresh the page, a new song starts playing, but the previous song keeps on playing. How do I get this to work properly so that the previous song stops?

It works in all browsers, except Firefox.

Here is what I have in my view:

<audio controls autoplay >
  <source src="<%= @song.mp3.url %>" type="audio/mp3">
Your browser does not support the audio element.
</audio>

<%= link_to "Reload", url_for(params) %>

My gemfile:

gem 'jquery-turbolinks'
gem 'jquery-ui-rails'
gem 'jquery-rails'
gem 'turbolinks'
gem 'jbuilder', '~> 2.0'
gem 'sdoc', '~> 0.4.0', group: :doc

Solution

  • Untested and feels a little hacky, but should stop audio from playing when turbolinks loads a new page:

    $(document).on('page:before-change', function(event) {
      $('audio').pause();
      return true;
    });