partey_workadventure/front/src/Components/SoundMeterWidget.svelte

54 lines
1.4 KiB
Svelte
Raw Normal View History

2021-05-28 15:48:58 +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-05-28 15:48:58 +02:00
2021-12-06 16:12:37 +01:00
export let stream: MediaStream | null;
2021-05-28 15:48:58 +02:00
let volume = 0;
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();
let display = false;
2021-12-06 16:12:37 +01:00
let error = false;
2021-05-28 15:48:58 +02:00
2021-06-01 16:17:36 +02:00
$: {
if (stream && stream.getAudioTracks().length > 0) {
display = true;
2021-06-01 16:17:36 +02:00
soundMeter.connectToSource(stream, new AudioContext());
2021-05-28 15:48:58 +02:00
2021-06-01 16:17:36 +02:00
if (timeout) {
clearInterval(timeout);
2021-12-06 16:12:37 +01:00
error = false;
2021-05-28 15:48:58 +02:00
}
2021-06-01 16:17:36 +02:00
timeout = setInterval(() => {
2021-12-06 16:12:37 +01:00
try {
volume = soundMeter.getVolume();
2021-12-06 16:12:37 +01:00
} catch (err) {
if (!error) {
console.error(err);
error = true;
}
2021-06-01 16:17:36 +02:00
}
}, 100);
} else {
display = false;
2021-06-01 16:17:36 +02:00
}
2021-05-28 15:48:58 +02:00
}
2021-06-01 16:17:36 +02:00
onDestroy(() => {
soundMeter.stop();
if (timeout) {
clearInterval(timeout);
}
2021-12-06 16:12:37 +01:00
});
2021-05-28 15:48:58 +02:00
</script>
<div class="sound-progress" class:active={display}>
2021-12-06 16:12:37 +01:00
<span class:active={volume > 5} />
<span class:active={volume > 10} />
<span class:active={volume > 15} />
<span class:active={volume > 40} />
<span class:active={volume > 70} />
2021-05-28 15:48:58 +02:00
</div>