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
190 views
in Technique[技术] by (71.8m points)

javascript - Create audio element, play it, and then remove element

I want to create an audio element when a button is clicked, play the audio, and then remove the audio when it is done playing Here is my code:

var x = document.getElementById("myAudio"); 

function playAudio() { 
  x.play(); 
} 
<audio id="myAudio">
  <source src="https://padlet-uploads.storage.googleapis.com/446844750/ca57ed6d83fff9890b4c9f2356e4e0c0/Single_Firework___Sound_Effect_HD__1_.mp3" type="audio/ogg">
</audio>
<button onclick="playAudio()" type="button">Play Audio</button>
question from:https://stackoverflow.com/questions/65892205/create-audio-element-play-it-and-then-remove-element

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

1 Reply

0 votes
by (71.8m points)

What I can understand from the link you posted is that you want to replay the audio from the beginning whenever the button is clicked. You can do it by setting the audio's currentTime to 0, then playing the audio:

var x = document.getElementById("myAudio"); 

function playAudio() { 
  x.currentTime = 0;
  x.play(); 
} 
<audio id="myAudio">
  <source src="https://padlet-uploads.storage.googleapis.com/446844750/ca57ed6d83fff9890b4c9f2356e4e0c0/Single_Firework___Sound_Effect_HD__1_.mp3" type="audio/ogg">
</audio>
<button onclick="playAudio()" type="button">Play Audio</button>

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

1.4m articles

1.4m replys

5 comments

56.9k users

...