0
votes

I'm putting together an online evaluation survey of synthesized speech. Part of the test requires that listeners are only allowed to hear a given WAV file play once (as an experimental control).

I've already figured out how to simply embed an audio clip with controls, so that it can be played several times:

    <audio controls>
    <source src="http://mypage.com/my_sound.wav" type="audio/wav">
    Your browser does not support the audio element
    </audio>

Furthermore, I've seen that some HTML questions have attempted to resolve the error of HTML audio playing back only once:

Audio played once only in Google Chrome in html

JavaScript + HTML5: Audio will only play once under certain circumstances

However, my question is how to code this (play HTML audio just once on-click) intentionally? Everything I've seen treats it as a bug to be fixed, rather than an intentional goal.

Cheers!

1

1 Answers

0
votes

I've been looking for this one too.

You have a few options.

The key to this stop is the onended event, which as you might expect, triggers when the fat lady stops singing.

<audio id="gilda">
  <source url="epic-aria.mp3">
</audio>

var fatLady = document.getElementById('gilda');
fatLady.onended = function() {
  fatLady.pause();
  fatLady.currentTime = 0; // << only needed if you're cutting off the sound misstep (before the end) and need to return to the beginning - but you might need it. Since you are doing some gaming, I figured that might come up...
};

There is also a jQuery way, which I am currently using. jQuery doesn't use onended, however - it uses ended instead...

var fatLady = $('#gilda');
fatLady.bind('ended', function(event) {
  fatLady
    .pause()
    .currentTime = 0; // << haven't field-tested this yet, but jquery didn't yell at me about it.

});

Let me know if you run into any hiccups.