Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
431 views
in Technique[技术] by (71.8m points)

html - javascript Audio object vs. HTML5 Audio tag

In a project recently when I loaded a sound with

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

It played fine unless a dialogue was opened (ie alert, confirm). However when I instead tried adding an audio tag in my html

<audio id="audio1">
    <source src="alarm.mp3" type="audio/mpeg" />
</audio>

and using

var myAudio1 = document.getElementById("audio1");
myAudio1.play()

it continued to play after a dialogue was opened. Does anyone know why this is? Also more generally what are the differences between the two ways to play sounds?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

According to this wiki entry at Mozilla <audio> 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 <audio> element like this:

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

That actually creates an audio element that you can use exactly like an <audio> 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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...