javascript Audio object vs. HTML5 Audio tag

后端 未结 5 1906
刺人心
刺人心 2020-12-07 20:25

In a project recently when I loaded a sound with

var myAudio = new Audio(\"myAudio.mp3\");
myAudio.play();

It played fine unless a dialogu

5条回答
  •  一向
    一向 (楼主)
    2020-12-07 20:54

    According to this wiki entry at Mozilla and new Audio() should be the same but it doesn't look like that is the case in practice. Whenever I need to create an audio object in JavaScript I actually just create an element like this:

    var audio = document.createElement('audio');
    

    That actually creates an audio element that you can use exactly like an element that was declared in the page's HTML.

    To recreate your example with this technique you'd do this:

    var audio = document.createElement('audio');
    audio.src = 'alarm.mp3'
    audio.play();
    

提交回复
热议问题