2021-06-01 16:17:36 +02:00
|
|
|
<script lang="typescript">
|
2021-12-06 16:12:37 +01:00
|
|
|
import { AudioContext } from "standardized-audio-context";
|
|
|
|
import { SoundMeter } from "../../Phaser/Components/SoundMeter";
|
|
|
|
import { onDestroy } from "svelte";
|
2021-06-01 16:17:36 +02:00
|
|
|
|
|
|
|
export let stream: MediaStream | null;
|
|
|
|
let volume = 0;
|
|
|
|
|
|
|
|
const NB_BARS = 20;
|
|
|
|
|
2021-06-15 18:34:11 +02:00
|
|
|
let timeout: ReturnType<typeof setTimeout>;
|
2021-06-01 16:17:36 +02:00
|
|
|
const soundMeter = new SoundMeter();
|
2021-06-03 10:17:38 +02:00
|
|
|
let display = false;
|
2021-12-06 16:12:37 +01:00
|
|
|
let error = false;
|
2021-06-01 16:17:36 +02:00
|
|
|
|
|
|
|
$: {
|
|
|
|
if (stream && stream.getAudioTracks().length > 0) {
|
2021-06-03 10:17:38 +02:00
|
|
|
display = true;
|
2021-06-01 16:17:36 +02:00
|
|
|
soundMeter.connectToSource(stream, new AudioContext());
|
|
|
|
|
|
|
|
if (timeout) {
|
|
|
|
clearInterval(timeout);
|
2021-12-06 16:12:37 +01:00
|
|
|
error = false;
|
2021-06-01 16:17:36 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
timeout = setInterval(() => {
|
2021-12-06 16:12:37 +01:00
|
|
|
try {
|
|
|
|
volume = parseInt(((soundMeter.getVolume() / 100) * NB_BARS).toFixed(0));
|
|
|
|
} catch (err) {
|
|
|
|
if (!error) {
|
|
|
|
console.error(err);
|
|
|
|
error = true;
|
|
|
|
}
|
2021-06-01 16:17:36 +02:00
|
|
|
}
|
|
|
|
}, 100);
|
2021-06-03 10:17:38 +02:00
|
|
|
} else {
|
|
|
|
display = false;
|
2021-06-01 16:17:36 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
onDestroy(() => {
|
|
|
|
soundMeter.stop();
|
|
|
|
if (timeout) {
|
|
|
|
clearInterval(timeout);
|
|
|
|
}
|
2021-12-06 16:12:37 +01:00
|
|
|
});
|
2021-06-01 16:17:36 +02:00
|
|
|
|
|
|
|
function color(i: number, volume: number) {
|
2021-12-06 16:12:37 +01:00
|
|
|
const red = (255 * i) / NB_BARS;
|
2021-06-01 16:17:36 +02:00
|
|
|
const green = 255 * (1 - i / NB_BARS);
|
|
|
|
|
|
|
|
let alpha = 1;
|
|
|
|
if (i >= volume) {
|
|
|
|
alpha = 0.5;
|
|
|
|
}
|
|
|
|
|
2021-12-06 16:12:37 +01:00
|
|
|
return "background-color:rgba(" + red + ", " + green + ", 0, " + alpha + ")";
|
2021-06-01 16:17:36 +02:00
|
|
|
}
|
|
|
|
</script>
|
|
|
|
|
2021-06-03 10:17:38 +02:00
|
|
|
<div class="horizontal-sound-meter" class:active={display}>
|
2021-06-11 11:29:36 +02:00
|
|
|
{#each [...Array(NB_BARS).keys()] as i (i)}
|
2021-12-06 16:12:37 +01:00
|
|
|
<div style={color(i, volume)} />
|
2021-06-01 16:17:36 +02:00
|
|
|
{/each}
|
|
|
|
</div>
|
|
|
|
|
|
|
|
<style lang="scss">
|
|
|
|
.horizontal-sound-meter {
|
2021-12-06 16:12:37 +01:00
|
|
|
display: flex;
|
|
|
|
flex-direction: row;
|
|
|
|
width: 50%;
|
|
|
|
height: 30px;
|
|
|
|
margin-left: auto;
|
|
|
|
margin-right: auto;
|
|
|
|
margin-top: 1vh;
|
2021-06-01 16:17:36 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
.horizontal-sound-meter div {
|
2021-12-06 16:12:37 +01:00
|
|
|
margin-left: 5px;
|
|
|
|
flex-grow: 1;
|
2021-06-01 16:17:36 +02:00
|
|
|
}
|
|
|
|
</style>
|