<script lang="typescript">
    import {SoundMeter} from "../Phaser/Components/SoundMeter";
    import {onDestroy} from "svelte";

    export let stream: MediaStream|null;
    let volume = 0;

    const NB_BARS = 5;

    let timeout;
    const soundMeter = new SoundMeter();

    $: {
        if (stream && stream.getAudioTracks().length > 0) {
            soundMeter.connectToSource(stream, new AudioContext());

            if (timeout) {
                clearInterval(timeout);
            }

            timeout = setInterval(() => {
                try{
                    volume = parseInt((soundMeter.getVolume() / 100 * NB_BARS).toFixed(0));
                    //console.log(volume);
                }catch(err){

                }
            }, 100);

        }
    }

    onDestroy(() => {
        soundMeter.stop();
        if (timeout) {
            clearInterval(timeout);
        }
    })
</script>


<div class="sound-progress" class:active={stream?.getAudioTracks().length > 0}>
    <span class:active={volume > 1}></span>
    <span class:active={volume > 2}></span>
    <span class:active={volume > 3}></span>
    <span class:active={volume > 4}></span>
    <span class:active={volume > 5}></span>
</div>
