Search code examples
javascriptjqueryhtmlsafarihtml5-audio

Changing <source> with HTML5 Audio works in Chrome but not Safari


I'm trying to make an HTML5 audio playlist that will work in each major browser: Chrome,Safari, Firefox, IE9+. However, I can't figure out how to change the sources in a cross browser compatible way.

UPDATED For example, changing the <source> tag's srcs works in Chrome but not Safari. While @eivers88's solution below using canPlayType works it seems easier to me just to change the <source> tag's srcs. Can anyone explain to me why my code directly below works in Chrome but not Safari?

JS:

var audioPlayer=document.getElementById('audioPlayer');
var mp4Source=$('source#mp4');
var oggSource=$('source#ogg');
$('button').click(function(){    
  audioPlayer.pause();
  mp4Source.attr('src', 'newFile.mp4');
  oggSource.attr('src', 'newFile.ogg');
  audioPlayer.load();
  audioPlayer.play();
});

HTML:

<button type="button">Next song</button>
<audio id="audioPlayer">
  <source id="mp4" src="firstFile.mp4" type="audio/mp4"/> 
  <source id="ogg" src="firstFile.ogg" type="audio/ogg" />                      
</audio>

Inspecting the HTML after the button click, the <source src=""/> does change in Safari, its just that the HTTP request is not made, so they the files don't get load()ed and play()ed. Does anyone have any thoughts on this?


Solution

  • Here is a working exapmle. It's a little bit different from what you have but hopefully this can be helpful.

    HTML:

    <button type="button">Next song</button>
    

    Javascript/jquery:

        var songs = [
        '1976', 'Ballad of Gloria Featherbottom', 'Black Powder' 
    ]
    var track = 0;
    var audioType = '.mp3'
    var audioPlayer = document.createElement('audio');
    
    $(window).load(function() {
    
        if(!!audioPlayer.canPlayType('audio/ogg') === true){
            audioType = '.ogg' //For firefox and others who do not support .mp3
        }
    
        audioPlayer.setAttribute('src', 'music/' + songs[track] + audioType);
        audioPlayer.setAttribute('controls', 'controls');
        audioPlayer.setAttribute('id', 'audioPlayer');
        $('body').append(audioPlayer);
        audioPlayer.load();
        audioPlayer.play();
    
    });
    
    $('button').on('click', function(){
        audioPlayer.pause();
        if(track < songs.length - 1){
            track++;
            audioPlayer.setAttribute('src', 'music/' + songs[track] + audioType);
            audioPlayer.load();
            audioPlayer.play();
        }
        else {
            track = 0;
            audioPlayer.setAttribute('src', 'music/' + songs[track] + audioType);
            audioPlayer.load();
            audioPlayer.play();
        }
    })