Search code examples
sveltehtml5-audio

Svelte Simple Audio Player Not Updating


I'm building a simple audio player using Svelte. The selectedMusic variable update every time I click on the next and previous buttons. But the audio won't update. How to fix this?

<script>
  import { onMount } from "svelte";

  export let src = [];
  let player;
  let active = 0;
  $: selectedMusic = src[active];
  let play = false;

  onMount(() => {
    player.volume = 0.5;
  });

  const next = () => {
    if (active < src.length - 1) {
      active++;
    } else {
      active = 0;
    }
    console.log(active);
    console.log(selectedMusic);
  };
  const previous = () => {
    if (active == 0) {
      active = src.length - 1;
    } else {
      active--;
    }
  };

  const togglePlay = () => {
    play ? player.pause() : player.play();
    play = !play;
  };
</script>

<audio bind:this={player} loop>
  <source src={selectedMusic} type="audio/mp3" />
</audio>

enter image description here


Solution

  • There's the .load() method which can be called to make the change of the src have an effect. Either reactively every time selectedMusic changes or at the end of previous() and next()

        $: selectedMusic = src[active];
        $: reload(selectedMusic)
    
        const reload = () => {
            if(!player) return
            player.load()
            if(play) player.play()
        }
    

    Here's a REPL