Reputation: 13
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
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:
Upvotes: 1
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