0

Using below code to make basic audio background music player to play files in a folder. On open and after Play (either button or on scale), it plays a random file in the Music folder. When that file ends, it loads another random file and plays it, then continues to repeat the process. The Question - Is it possible add a button onclick = (i.e. Next Song) to trigger the "ended" event and trigger the next song when clicked. I think I need to add a music.stop() also. I'm just trying to force the playing song to end and have the loop load the next song. It appears that the "ended" event is a read only event and can't be manually changed to a true.

    <html>  
<head>
<body> 
<!-- <audio id="player" controls><source src="music/0.mp3" type="audio/mp3"></audio> -->
<div align="center" id="soundtrack">  
<script>
var WhichSong="Music2/song"+(Math.floor(Math.random()*23))+".mp3"

document.getElementById('soundtrack').innerHTML="<audio controls id='player'><source src=\"" + WhichSong + "\"></source>Your browser does not support the audio element.</audio>";

    var x = 0;
    var music = document.getElementById("player");
    music.addEventListener("ended", function() {
    x=x+1;
    music.src = "Music2/song"+(Math.floor(Math.random()*23))+".mp3";
    music.load();
    music.play();       
    });
    </script>
    <br/>
  <button onclick="document.getElementById('player').play()">Play Music</button> 
  <button onclick="document.getElementById('player').pause()">Pause Music</button>
  <button onclick="document.getElementById('player').muted=true">Mute</button>
  <button onclick="document.getElementById('player').muted=false">Un-mute</button>
  <button onclick="document.getElementById('player').volume += 0.1">Vol +</button> 
  <button onclick="document.getElementById('player').volume -= 0.1">Vol -</button>

</div>  
</body>

Nordii
  • 479
  • 1
  • 5
  • 15
nickhog
  • 5
  • 3
  • That sounds like Javascript (ECMAScript), not Java. – Sascha May 16 '19 at 11:52
  • Possible duplicate of [How to call multiple JavaScript functions in onclick event?](https://stackoverflow.com/questions/3910736/how-to-call-multiple-javascript-functions-in-onclick-event) – Sascha May 16 '19 at 11:52

1 Answers1

1

The easiest way is by assigning the event listener to a variable and then calling that function from your onclick.

var endedListener = function() {
    x=x+1;
    music.src = "Music2/song"+(Math.floor(Math.random()*23))+".mp3";
    music.load();
    music.play();       
    };
music.addEventListener("ended", endedListener);

<button onclick="endedListener()">Next</button>

Keep in mind that calling endedListener does not actually stop the audio from playing. It just triggers your own function logic.

Max Meijer
  • 1,530
  • 1
  • 14
  • 23
  • Once I figured out the right place to add your code, This was the help I needed to get this little script to do everything I needed it to do. – nickhog May 28 '19 at 23:18