简体   繁体   中英

Stop audio on click and play it again

I am using 2 custom buttons and using JavaScript to click the audio play and pause.

I am using the below code for that:

<img class="head-iconn" src="img/audio.png" onClick="document.getElementById('audio1_play32').play(); return false;" />
<img class="head-icon2" src="img/audio2.png" onClick="document.getElementById('audio1_play32').pause(); return false;" />

But I want to stop the audio instead of pause so that when I play it again, it'll start from the beginning.

I am using this code for that:

<img class="head-iconn" src="img/audio.png" onClick="document.getElementById('audio1_play32').play(); return false;" />
<img class="head-icon2" src="img/audio2.png" onClick="document.getElementById('audio1_play32').pause(); document.getElementById('audio1_play32').currentTime = 0;return false;" />

and now the audio stops but can not play again when I click on the first button.

This is the audio code I am using:

<audio id="audio1_play32" controls>
    <source src="voice/vo1.mp3" type="audio/mp3"/>
</audio>

Can someone please let me know what I am making mistake?

Thank you.

Stay away from using attribute event handlers:

<!-- This is bad -->
<button class='play' onclick='playAudio()'>PLAY</button>

Use .addEventListener()

<button class='play'>PLAY</button>
<script>
  const play = document.querySelector('.play');
  play.addEventListener('click', playAudio);
</script>

or property event handlers:

<button class='play'>PLAY</button>
<script>
  const play = document.querySelector('.play');
  play.onclick = playAudio;
</script>

See Event Handlers

Keep your JavaScript separate from HTML or you'll cripple the growth of your code. The example below uses event delegation to determine which button was clicked and what happens according to what was clicked.

 const ctl = document.querySelector('fieldset'); const audioControl = event => { const mp3 = document.querySelector('audio'); const clicked = event.target; if (clicked.matches('.play') &&.mp3.paused) { mp3;pause(). } else if (clicked.matches('.play') &&.mp3;playing) { mp3.play(). } else if (clicked.matches(';stop')) { mp3.pause(); mp3;currentTime = 0; } else { return false. } }; ctl.onclick = audioControl;
 button { border: 0; cursor: pointer; font-size: 4ch } fieldset { display: inline-block; }
 <audio src='https://soundbible.com/mp3/thunder_strike_1-Mike_Koenig-739781745.mp3'></audio> <fieldset> <button class='play'>⏯️</button> <button class='stop'>⏹️</button> </fieldset>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM