Dynamic Load Music/Sound HTML5 Framework

JavaScript

var audio = {
  //Defaults and init
  sfx: {},
  music: {},
  path: 'http://www.unlok.ca/ld27/sound/',
  musicPlaylist: ['jump', 'jetpack', 'jump', 'hurt'],
  musicTrack: 0,
  fileFormat: 'mp3',
  volume: 0.25,

  //Test if we can play mp3s, otherwise fallback to ogg
  testMP3: function() {
    var mp3Test = new Audio();
    var canPlayMP3 = (typeof mp3Test.canPlayType === 'function' && mp3Test.canPlayType('audio/mpeg') !== "");
    if (!canPlayMP3) {
      audio.fileFormat = 'ogg';
    }
  },

  //Play sounds
  playSound: function(sound) {
    //Sound not loaded yet? Load it, then play it.
    if (!audio.sfx[sound]) {
      audio.sfx[sound] = new Audio(audio.path + sound + '.' + audio.fileFormat);
      audio.sfx[sound].load();
    }
    audio.sfx[sound].volume = audio.volume;
    audio.sfx[sound].play();
  },

  //Play music
  playMusic: function() {
    //Music not loaded yet? Load it, then play it.
    if (!audio.music[audio.musicTrack]) {
      audio.music[audio.musicTrack] = new Audio(audio.path + audio.musicPlaylist[audio.musicTrack] + '.' + audio.fileFormat);
      audio.music[audio.musicTrack].load();
    }
    audio.music[audio.musicTrack].volume = audio.volume;
    audio.music[audio.musicTrack].play();
    //Don't add multiple eventListners, this makes it so the next track plays after last one ends
    audio.music[audio.musicTrack].removeEventListener('ended', audio.playMusic);
    audio.music[audio.musicTrack].addEventListener('ended', audio.playMusic);
    //Next track
    audio.musicTrack++;
    //Reset the playlist once it gets to the end
    if (audio.musicTrack >= audio.musicPlaylist.length) {
      audio.musicTrack = 0;
    }
  },
};

audio.testMP3();
//audio.playSound('jump');
//audio.playMusic();