Setting up an mp3 player that keeps playing during navigation

Setting up an mp3 player that keeps playing during navigation responsiveDuring my recent project, working on a radio stations website, I came across an interesting requirement:

Keep the mp3 playing, while changing the page within the site.

All of this had to be done within the existing wordpress installation.

One might think it cannot be done. If a user clicks a link, he will leave current page, and the player which was embedded on the old page, behind. Stopping the playback.

Fortunately, this had already been done, and someone came up with a nice Ajax (actually AJAH) solution:

  • Change all links so you Do not actually leave the page
  • Instead reload all page parts except the mp3 player with Ajax (AJAH)
  • Then, change the browsers history.

While this is a rather elaborate hack for this particular problem, it actually works rather well in practice. You can freely move around on the website while the player just stays there.

Some considerations:

  • Turn it off if you don’t need it (the player is not playing)
  • Set up a website structure where this is easily possible, without having to adress a lot of divs. This keeps your javascript clean and simple.
    • header
    • player
    • content
    • footer
  • Use only on internal links

This solution will also preserve some bandwidth. And you are in good neighborhood with big players like Facebook and Google who employ this technique all the time.

What is required?

  • A HTML5 or Flash Player
    Doesnt really matter, as we have to work around the player.
  • jQuery
  • jQuery History to modify the Browser history (make back buttons work etc.)

Some JavaScript code

  • jQuery delegate to intercept all internal <a> and <forms>:
    • jQuery(document).delegate(„a[href^=’/‘]“, ‚click‘, function(event) { … }
    • jQuery(document).delegate(„form[action^='“ + LoungeFM.siteURL + „‚]“, ’submit‘, function(event) { … }
    • event.preventDefault();
  • jQuery history
    • History.Adapter.bind(window, ’statechange‘, function(event) { … }
      • Load all the html
        Call Google Analytics to track the pagecall
      • Change the title
        document.title = obj.find(‚title‘).text();

All in all a complex solution for a limitation of html, which in the end works really well in the web and on mobile (WebKit) devices. Interesting how easily it can be done using jQuery, however there were a number of issues to consider like the title and tracking.

Written by Ben