John M. John M. - 4 months ago 11
jQuery Question

I only want my audio mp3 file to play one time and it's not happening

I have an audio that the user can start and stop. That works fine but I only want the audio to play through one time. Currently it keeps looping and I definitely don't want that. Can someone tell me how I can make this play through one time then stop? Thank you.

HTML5

<div class="container">
<h3>A word on meditation</h3>
<button id="play">Play</button> &nbsp;<button id="pause">Stop</button>
</div>


JS

var audioElement = document.createElement('audio');
audioElement.setAttribute('src', 'audio/thoseWhoMeditate.mp3');

audioElement.addEventListener('ended', function() {
this.currentTime = 0;
this.play();
}, false);

$('#play').click(function() {
audioElement.play();
});

$('#pause').click(function() {
audioElement.pause();
});

Answer

Not sure about jquery instructions, but maybe change the event type to load:

var audioElement = document.createElement('audio');
audioElement.setAttribute('src', 'audio/thoseWhoMeditate.mp3');

audioElement.addEventListener('load', function() {
    this.currentTime = 0;
    this.play();
}, false);

$('#play').click(function() {
    audioElement.play();
});

$('#pause').click(function() {
    audioElement.pause();
});