Wolfgang
Wolfgang

Reputation: 13

Allow play audio once html

I am trying to limit subjects to play an audio file only once in my experiment. I am using the following html code:

<audio src="sound.mp3" type="audio/mp3" preload="auto" controls="controls" oncontextmenu="return false;">Audio could not be loaded.</audio>

Is there a way to do it using html? If not how can I adapt this to javascript?

Thank you!

Upvotes: 0

Views: 2950

Answers (2)

Ryan Wheale
Ryan Wheale

Reputation: 28440

It depends on what your rules are for "play an audio file only once": is when the user hits the play button or is it after the user listens to the entire track?

You cannot disable the native audio controls while still having them visible. If you want the ability to manipulate audio controls, you will need to use your own controls using JS, HTML, and CSS. There are libraries out there for this already.

Also, if you are kind, you should give the user the ability to stop the audio after she hits play.

Here's what I would do:

  • use a plugin to add your own player controls
  • only show the play / stop button
  • write javascript that marks the file as "played" when...
    1. the player hits the stop button, or
    2. when the end of the song is reached
  • Once the audio is considered "played", disable the play button

Upvotes: 1

Sishaar Rao
Sishaar Rao

Reputation: 370

The way I would do this is put the audio in a div called audioDiv

<div id="audioDiv">
    <audio onclick="playedOnce()" src="sound.mp3" type="audio/mp3" preload="auto" controls="controls" oncontextmenu="return false;">Audio could not be loaded.</audio>
</div>

and then add this javascript method somewhere

function playedOnce(){
    var children = document.getElementById("audioDiv").getElementsByTagName('*');
    for(var i = 0; i < children.length; i++){
        children[i].disabled = true;
    }

}

Now obviously this is a shell method that assumes you only have one audio, so perhaps your javascript method takes in a parameter to determine which one to disable etc. Additionally, this is assuming the user doesn't simply refresh the page. If you want to keep it hidden despite the user refreshing the page, I would look into PHP sessions!

Hope this helps!

Upvotes: 0

Related Questions