<html>
  <head>
    <title>MediaSessionDOMTest1</title>
  </head>
  <body>
    <script>
      function updatePositionState(event) {
        if (event.target != active) {
          return;
        }
        navigator.mediaSession.setPositionState({
          duration: parseFloat(event.target.duration),
          position: parseFloat(event.target.currentTime),
          playbackRate: 1,
        });
      }

      function updateMetadata() {
        navigator.mediaSession.metadata = active.metadata;
      }

      function getTrack(offset) {
        console.log("" + active.id + " " + offset);
        const nextId = Math.min(
          tracks.length - 1,
          Math.max(0, parseInt(active.id) + offset)
        );
        return tracks[nextId];
      }

      navigator.mediaSession.setActionHandler("play", async () => {
        updateMetadata();
        await active.play();
      });

      navigator.mediaSession.setActionHandler("pause", () => {
        active.pause();
      });

      navigator.mediaSession.setActionHandler("previoustrack", () => {
        active = getTrack(-1);
      });

      navigator.mediaSession.setActionHandler("nexttrack", () => {
        active = getTrack(1);
      });

      const audio1 = document.createElement("audio");
      audio1.src = "audio/owl.mp3";
      audio1.addEventListener("timeupdate", updatePositionState);
      audio1.metadata = new window.MediaMetadata({
        title: "hoot",
        artist: "owl",
        album: "hoots",
        artwork: [
          {
            src: "images/test.gif",
            type: "image/gif",
            sizes: "265x199",
          },
        ],
      });
      audio1.id = 0;

      const audio2 = document.createElement("audio");
      audio2.src = "audio/owl.mp3";
      audio2.addEventListener("timeupdate", updatePositionState);
      audio2.metadata = new window.MediaMetadata({
        title: "hoot2",
        artist: "stillowl",
        album: "dahoots",
        artwork: [
          {
            src: "images/test.gif",
            type: "image/gif",
            sizes: "265x199",
          },
        ],
      });
      audio2.id = 1;

      const audio3 = document.createElement("audio");
      audio3.src = "audio/owl.mp3";
      audio3.addEventListener("timeupdate", updatePositionState);
      audio3.metadata = new window.MediaMetadata({
        title: "hoot3",
        artist: "immaowl",
        album: "mahoots",
        artwork: [
          {
            src: "images/test.gif",
            type: "image/gif",
            sizes: "265x199",
          },
        ],
      });
      audio3.id = 2;

      const tracks = [audio1, audio2, audio3];
      let active = audio1;

      window.onload = async () => {
        active = getTrack(0);
        updateMetadata();
        await active.play();
      };
    </script>
  </body>
</html>
