I am trying to add a stop and play button for an audio element in javascript as per below.
As it stands the audio automatically starts on page load with the autoplay set and I would like to be able to use the stop icon to stop the stream and then the play icon to start it again.
With the code below, I can have the audio stream autostart as expected and also the stop icon works, but if I add code to try and have the stream start again, it will not work. Checking the console it doesn't even seem to recognise the stop button at all, only the play button (when I add the play icon).
<head>
<script type="text/javascript">
window.onload = function() {
var a = document.getElementById("audiostop");
a.onclick = function() {
var player = document.getElementById('radio');
player.pause();
console.log("Pressed Stop");
return false;
}
}
</script>
</head>
<body>
<a id="audiostop" class="fa fa-stop" style="color: #ed1a42;"></a>
<a id="audiostart" class="fa fa-play" style="color: #ed1a42;"></a>
<audio controls id="radio" autoplay loop height="" width="">
<source src="<?php echo $player_stream; ?>" type="audio/mpeg">
</audio>
</body>
If I add this:
<script type="text/javascript">
window.onload = function() {
var a = document.getElementById("audiostart");
a.onclick = function() {
var player = document.getElementById('radio');
player.start();
console.log("Pressed Start");
return false;
}
}
</script>
Then only the 'play' icon registers in the console as working, the 'stop' one stops working.
I'm not too familiar with Javascript, can anyone lend a hand?
Thank you.
In one script tag, what happens if you try this?
window.onload = function () {
var player = document.getElementById("radio");
var start = document.getElementById("audiostart");
var stop = document.getElementById("audiostop");
start.onclick = function () {
player.play();
console.log("Pressed Start");
};
stop.onclick = function () {
player.pause();
console.log("Pressed Stop");
};
};