Reputation: 35
Here is a JSFiddle:
HTML:
<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">play!</a>
JS:
var yourAudio = document.getElementById('yourAudio'),
ctrl = document.getElementById('audioControl');
ctrl.onclick = function () {
// Update the Button
var pause = ctrl.innerHTML === 'pause!';
ctrl.innerHTML = pause ? 'play!' : 'pause!';
// Update the Audio
var method = pause ? 'pause' : 'play';
yourAudio[method]();
// Prevent Default Action
return false;
};
Instead of using the words 'play!' and 'pause!' how can I toggle between custom images I've created for play and pause?
In addition to this, is there a way to make the 'play' button return after the audio is done playing. As of now when the audio is done playing it stays on pause.
Upvotes: 1
Views: 489
Reputation: 11318
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;
});
Second part using ended event (really nice feature). Jsfiddle:http://jsfiddle.net/8LczkwLz/
P.S. You will have to add image in HTML, too, of course, check fiddle. Hope all is clear.
Upvotes: 1