Changing with HTML5 Audio works in Chrome but not Safari

后端 未结 2 630
礼貌的吻别
礼貌的吻别 2021-01-06 12:39

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 c

相关标签:
2条回答
  • 2021-01-06 12:55

    For some reason, Safari can't use the <source> tags for swapping between songs but Chrome can. Just changing what gets loaded into the src attribute on the <audio> tag works on both Chrome and Safari but then there is the ogg vs. mp3 issue.

    I guess one way to get around this ogg vs. mp3 issue is to use Modernizr does feature detection to load the ogg mime-type in Firefox and the mp3 in Chrome/Safari. Here's a reference on that: Detecting html5 audio support with Modernizr.

    0 讨论(0)
  • 2021-01-06 12:57

    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();
        }
    })
    
    0 讨论(0)
提交回复
热议问题