Reputation: 289
I'am beginner in HTML5 and not even middle in JS, but I'am trying to figure out how to correctly use <audio>
and smth else... so i've got this question... my html:
<i class='some_icon' onclick='play();'>
<audio src='some_mp3.mp3' id='player'></audio>
</i>
Now when I click on the icon I want some mp3 file play and it works because I wrote this js:
function play() {
var my = document.getElementById('player');
if (my.paused) {
my.play();
} else {
my.pause();
my.currentTime = 0
}
}
BUT, besides, I want to change my icon WHEN that mp3 file ENDS... how can I do that? Any help will be greatly appreciated :)
Upvotes: 2
Views: 3059
Reputation: 28563
I know this was answered/accepted yesterday but i just thought I'd share a full working bit of code for future users benefit. (the sound clip is only 4 secs long)
function play() {
var my = document.getElementById('player');
my.currentTime = 0;
/**this one loops***/
if ($('.btn').find('span i').hasClass('fa-stop')) {
$('.btn').find('span i').removeClass('fa-stop').addClass('fa-play-circle');
$('.texto').text("Play");
}
if (my.paused) {
my.play();
} else {
my.pause();
my.currentTime = 0;
}
my.addEventListener("ended", function(e) {
$('.btn').find('span i').removeClass('fa-play-circle').addClass('fa-stop');
$('.texto').text("Stop");
});
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css" rel="stylesheet" type="text/css" />
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Audio Icon Toggle</title>
</head>
<body>
<div id="music">
<h2>Audio Icon Toggle</h2>
<button type="button" class="btn btn-success" data-toggle="collapse" data-target="#player" onclick="play();"><span><i class="fa fa-play-circle" aria-hidden="true"></i> <span class="texto">Play</span></span>
<audio src="http://www.rachelgallen.com/monkey.mp3" id="player" class="collapse"></audio>
</button>
</div>
</body>
</html>
Upvotes: 0
Reputation: 10083
Here is the code to trigger some code when your audio ( or video ) ends:
var my = document.getElementById('player');
my.addEventListener("ended", function(e){
// here goes your code to change the icon
}, false);
Upvotes: 7