cifkao / html-midi-player

🎹 Play and display MIDI files on the web
https://cifkao.github.io/html-midi-player/
BSD 2-Clause "Simplified" License
630 stars 56 forks source link

Add a looping option #51

Closed jirakova closed 2 years ago

jirakova commented 2 years ago

It would be nice to specify in the midi-player tags that, once Play is pressed, the song should continue on repeat. (If the option is already there, pardon me. I am at the ignorant user level; if it isn't in the examples linked in README, I will never find it.)

cifkao commented 2 years ago

Yes, that would be useful and this is not the first time it has been requested, but so far it is not supported out of the box (see #8).

However, it's actually pretty straightforward to implement on the user side. Adding this bit of JavaScript to your page should do the trick:

<script>
document.querySelector("midi-player").addEventListener("stop", function(event) {
  if (event.detail.finished) {
    this.start();
  }
});
</script>

Here is a codepen to try it out: https://codepen.io/cifkao/pen/JjLGJzM

jirakova commented 2 years ago

I've tried it and this script makes the first MIDI player on the page loop, not the rest. I consulted with a friend and got the following recommendations:

  1. To loop all MIDI players on the page, use
    <script>
    [].forEach.call(document.querySelectorAll("midi-player"), function (player) {
    player.addEventListener("stop", function(event) {
         if (event.detail.finished) {
                 this.start();
               }
     });
    });
    </script>
  2. To loop only one MIDI player, use:
    <script>
    [].forEach.call(document.querySelectorAll(".looping"), function (player) {
    player.addEventListener("stop", function(event) {
         if (event.detail.finished) {
                 this.start();
               }
     });
    });
    </script>

    and

    <midi-player class="looping" sound-font src="mysong.mid">

    The latter is just what I needed. Your MIDI player is now a proud part of my music gallery. Credit provided, of course. :)

cifkao commented 2 years ago

Looping is now implemented and released in v1.5.0!

<midi-player src="song.mid" loop></midi-player>