Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
196 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 Answer

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...