feat(music): refactor and basic cava implementation

This commit is contained in:
Pihkaal
2024-02-11 23:15:04 +01:00
parent 9084eccf17
commit 1a76054261
6 changed files with 212 additions and 120 deletions

View File

@@ -0,0 +1,82 @@
import { Fragment, useRef, useEffect, useState } from "react";
import { ProgressBar, Group, useFrame, useTerminal } from "react-dom-curse";
import { theme } from "~/utils/theme";
export const Cava = () => {
const { width } = useTerminal();
const audioContext = useRef(new AudioContext());
const analyser = useRef(audioContext.current.createAnalyser());
const bufferLength = useRef(analyser.current.frequencyBinCount);
const dataArray = useRef(new Uint8Array(bufferLength.current));
const [barHeights, setBarHeights] = useState(
new Array<number>(Math.round(width / 3)).fill(0),
);
useEffect(() => {
const audioElement = document.querySelector("audio");
if (!audioElement) return;
const audioSource =
audioContext.current.createMediaElementSource(audioElement);
audioSource.connect(analyser.current);
analyser.current.connect(audioContext.current.destination);
audioElement.play();
return () => {
audioSource.disconnect();
analyser.current.disconnect();
};
}, []);
useFrame(() => {
analyser.current.getByteFrequencyData(dataArray.current);
const barCount = Math.floor(width / 3);
const barHeights = [];
for (let i = 0; i < barCount; i++) {
const startIndex = Math.floor((i / barCount) * bufferLength.current);
const endIndex = Math.floor(((i + 1) / barCount) * bufferLength.current);
const slice = dataArray.current.slice(startIndex, endIndex);
const sum = slice.reduce((acc, val) => acc + val, 0);
const average = sum / slice.length;
barHeights.push(average);
}
setBarHeights(barHeights);
});
return (
<Group
x={0}
y={0}
width={width}
height={5}
style={{ foreground: theme.white }}
>
{barHeights.map((height, x) => (
<Fragment key={x}>
<ProgressBar
x={x * 3}
y={4}
size={5}
min={0}
max={255}
value={height}
orientation="top"
/>
<ProgressBar
x={x * 3 + 1}
y={4}
size={5}
min={0}
max={255}
value={height}
orientation="top"
/>
</Fragment>
))}
</Group>
);
};

View File

@@ -0,0 +1,49 @@
import { useEffect, useRef, useState } from "react";
import { parseBlob, type IAudioMetadata } from "music-metadata-browser";
import song from "/audio/colorful-flowers.mp3";
import { Kitty } from "../Kitty";
import { Cava } from "./Cava";
import { SpotifyPlayer } from "./SpotifyPlayer";
export const Music = () => {
const [metadata, setMetadata] = useState<IAudioMetadata>();
const [currentTime, setCurrentTime] = useState(0);
const audio = useRef<HTMLAudioElement>(null);
const handleTimeUpdate = () => {
setCurrentTime(audio.current?.currentTime ?? 0);
};
useEffect(() => {
if (metadata) return;
void fetch(song)
.then(r => r.blob())
.then(b => parseBlob(b))
.then(setMetadata);
}, [metadata]);
return (
<>
<audio ref={audio} src={song} onTimeUpdate={handleTimeUpdate} loop />
{metadata && audio.current && (
<>
<Kitty className="flex-1 select-none">
<SpotifyPlayer
title={metadata.common.title ?? "Unknown"}
artist={metadata.common.artist ?? "Unknown"}
album={metadata.common.album ?? "Unknown"}
played={currentTime}
duration={audio.current.duration}
/>
</Kitty>
<Kitty className="flex-1">
<Cava />
</Kitty>
</>
)}
</>
);
};

View File

@@ -0,0 +1,79 @@
import { useEffect } from "react";
import { Bar, Frame, Group, Text, useTerminal } from "react-dom-curse";
import { theme } from "~/utils/theme";
const formatDurationMSS = (duration: number) => {
duration = Math.floor(duration);
const minutes = Math.floor(duration / 60);
const seconds = duration % 60;
return `${minutes}:${seconds.toString().padStart(2, "0")}`;
};
export const SpotifyPlayer = (props: {
title: string;
artist: string;
album: string;
played: number;
duration: number;
}) => {
const { width } = useTerminal();
const time = `${formatDurationMSS(props.played)}/${formatDurationMSS(
props.duration,
)}`;
return (
<Group
x={0}
y={0}
width={width}
height={5}
style={{ foreground: theme.white }}
>
<Frame x={0} y={0} width={width} height={5} border="single">
<Text x={0} y={0} style={{ foreground: theme.cyan, bold: true }}>
{props.title} · {props.artist}
</Text>
<Text x={0} y={1} style={{ foreground: theme.yellow }}>
{props.album}
</Text>
<Group x={0} y={2} width={width} height={1}>
<Bar
x={0}
y={0}
style={{
foreground: theme.green,
background: "#55576d",
bold: true,
}}
char=" "
size={width}
direction="right"
/>
<Bar
x={0}
y={0}
style={{
foreground: "#55576d",
background: theme.green,
bold: true,
}}
char=" "
size={width * (props.played / props.duration)}
direction="right"
/>
<Text x={Math.floor(width / 2 - time.length / 2 - 1)} y={0}>
{time}
</Text>
</Group>
</Frame>
<Text x={1} y={0} style={{ foreground: theme.magenta }}>
{"Playback".substring(0, Math.min(8, width - 2))}
</Text>
</Group>
);
};

View File

@@ -1,106 +0,0 @@
import { useEffect, useRef, useState } from "react";
import { Bar, Frame, Group, Text, useTerminal } from "react-dom-curse";
import { theme } from "~/utils/theme";
import { parseBlob, type IAudioMetadata } from "music-metadata-browser";
import song from "/audio/colorful-flowers.mp3";
const formatDurationMSS = (duration: number) => {
duration = Math.floor(duration);
const minutes = Math.floor(duration / 60);
const seconds = duration % 60;
return `${minutes}:${seconds.toString().padStart(2, "0")}`;
};
export const MusicPlayer = () => {
const { width } = useTerminal();
const [metadata, setMetadata] = useState<IAudioMetadata>();
const audio = useRef<HTMLAudioElement>();
useEffect(() => {
if (audio.current) return;
audio.current = new Audio(song);
void fetch(song)
.then(r => r.blob())
.then(b => parseBlob(b))
.then(d => {
void audio.current?.play();
setMetadata(d);
});
}, []);
if (!audio.current) return null;
const played = audio.current.currentTime;
const duration = audio.current.duration;
const time = `${formatDurationMSS(played)}/${formatDurationMSS(duration)}`;
return (
<Group
x={0}
y={0}
width={width}
height={5}
style={{ foreground: theme.white }}
>
<Frame x={0} y={0} width={width} height={5} border="single">
{metadata ? (
<>
<Text x={0} y={0} style={{ foreground: theme.cyan, bold: true }}>
{metadata.common.title ?? "Unknown"} ·{" "}
{metadata.common.artist ?? "Unknown"}
</Text>
<Text x={0} y={1} style={{ foreground: theme.yellow }}>
{metadata.common.album ?? "Unknown"}
</Text>
<Group x={0} y={2} width={width} height={1}>
<Bar
x={0}
y={0}
style={{
foreground: theme.green,
background: "#55576d",
bold: true,
}}
char=" "
size={width}
direction="horizontal"
/>
<Bar
x={0}
y={0}
style={{
foreground: "#55576d",
background: theme.green,
bold: true,
}}
char=" "
size={width * (played / duration)}
direction="horizontal"
/>
<Text x={Math.floor(width / 2 - time.length / 2 - 1)} y={0}>
{time}
</Text>
</Group>
</>
) : (
<>
<Text x={0} y={0}>
No playback found.
</Text>
</>
)}
</Frame>
<Text x={1} y={0} style={{ foreground: theme.magenta }}>
{"Playback".substring(0, Math.min(8, width - 2))}
</Text>
</Group>
);
};

View File

@@ -1,5 +0,0 @@
import { type FunctionComponent } from "react";
export const MusicVisualizer: FunctionComponent = () => (
<div className="h-full w-full bg-red-500"></div>
);