Reputation: 35
Here is a js fiddle:
HMTL:
<audio id="yourAudio" preload='none'>
<source src='http://dl.dropbox.com/u/1538714/article_resources/song.m4a' type='audio/mpeg' />
</audio>
<a href="#" id="audioControl"><img src="http://codropspz.tympanus.netdna-cdn.com/codrops/wp-content/uploads/2010/01/play1-150x150.png"></a>
JS:
var yourAudio = document.getElementById('yourAudio'),
ctrl = document.getElementById('audioControl');
ctrl.onclick = function () {
pause_html='<img src="https://cdn2.iconfinder.com/data/icons/media-and-navigation-buttons-square/512/Button_4-128.png">';
play_html='<img src="http://codropspz.tympanus.netdna-cdn.com/codrops/wp-content/uploads/2010/01/play1-150x150.png">';
// Update the Button
var pause = ctrl.innerHTML === pause_html;
ctrl.innerHTML = pause ? play_html : pause_html;
// Update the Audio
var method = pause ? 'pause' : 'play';
yourAudio[method]();
// Prevent Default Action
return false;
};
document.getElementById('yourAudio').addEventListener('ended', function(){
ctrl.innerHTML=play_html;
});
Is there a way to disable the pause button from being clicked/pausing the audio? The audio files I will be playing last at most a few seconds so there isn't really a need to pause in the middle of them. That being said I want the pause button to display while the audio is playing just as a visual cue to the user.
Upvotes: 1
Views: 988
Reputation: 26
In general I'd think you would always give the user the ability to pause something if they wish, just from a usability standpoint. However to answer your question, I would utilize .preventDefault() and an if else statement.
//Check the whether you are playing audio
if(ctrl.innerHTML == play_html){
// Update the Button
var pause = ctrl.innerHTML === pause_html;
ctrl.innerHTML = pause ? play_html : pause_html;
// Update the Audio
var method = pause ? 'pause' : 'play';
yourAudio[method]();
}else{
ctrl.preventDefault();
}
This was tested and worked in your jsfiddle
Upvotes: 1