Playing sound with JavaScript

前端 未结 3 2031
-上瘾入骨i
-上瘾入骨i 2020-12-03 20:38

Doesn\'t matter what I do, I simply can\'t get this to play a sound in Firefox or IE, or Chrome for that matter.





        
3条回答
  •  清歌不尽
    2020-12-03 20:54

    Try This Method, to play sound in all your browsers :

    function playSound(soundfile_ogg, soundfile_mp, soundfile_ma) {
        if ("Audio" in window) {
            var a = new Audio();
            if (!!(a.canPlayType && a.canPlayType('audio/ogg; codecs="vorbis"')
                    .replace(/no/, '')))
                a.src = soundfile_ogg;
            else if (!!(a.canPlayType && a.canPlayType('audio/mpeg;').replace(/no/,
                    '')))
                a.src = soundfile_mp;
            else if (!!(a.canPlayType && a.canPlayType(
                    'audio/mp4; codecs="mp4a.40.2"').replace(/no/, '')))
                a.src = soundfile_ma;
            else
                a.src = soundfile_mp;
    
            a.autoplay = true;
            return;
        } else {
            alert("Time almost up");
        }
    }
    

    to play the sound, do something like this:

    playSound("/file/horse.wav", "/file/horse.mp3","/file/horse.m4a");
    

提交回复
热议问题