feat(web): new look, part 2: the player with a live spectrogram

- A spectrogram drawn in the browser from the sound being played: the last
  seconds, time running to the right and ending now, low notes at the bottom,
  brighter where there is more energy. Small in the player bar, large in the
  full-screen player. It works the same for a friend's track, since its audio
  comes through this server.
- It is drawn only while something plays and the page is in view, and with
  reduced motion it is redrawn four times a second; where the browser has no
  Web Audio it stays empty and nothing else changes.
- The play button is round, in the colour of this server and in the friend
  colour for a friend's track.
- The bar and the full-screen player show the name of the friend whose server
  a track comes from, and nothing for this server's own music.
This commit is contained in:
tgiachi 2026-11-13 17:17:57 +01:00
commit fdf1ebfabc

View file

@ -0,0 +1,91 @@
import { useEffect, useRef } from 'react'
import { useTranslation } from 'react-i18next'
import { hasAnalyser, readBins } from '@/player/analyser'
import { currentTrack, usePlayer } from '@/player/store'
import { ColumnBuffer, rowsFromBins } from '@/player/spectrum'
import { cn } from '@/lib/utils'
/** A new column every this many milliseconds (every quarter of a second with reduced motion: it is a picture, not a show). */
const FRAME_MS = 80
const REDUCED_FRAME_MS = 250
function colourOf(canvas: HTMLCanvasElement): [number, number, number] {
const match = /rgba?\(\s*(\d+)[,\s]+(\d+)[,\s]+(\d+)/.exec(getComputedStyle(canvas).color)
return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : [255, 255, 255]
}
function draw(canvas: HTMLCanvasElement, columns: number[][], rows: number) {
const ctx = canvas.getContext('2d')
if (!ctx) return
const ratio = window.devicePixelRatio || 1
const width = Math.round(canvas.clientWidth * ratio)
const height = Math.round(canvas.clientHeight * ratio)
if (canvas.width !== width) canvas.width = width
if (canvas.height !== height) canvas.height = height
ctx.clearRect(0, 0, width, height)
const [r, g, b] = colourOf(canvas)
const gap = 2 * ratio
const cols = columns.length
const cellW = (width - gap * (cols - 1)) / cols
const cellH = (height - gap * (rows - 1)) / rows
for (let c = 0; c < cols; c++) {
for (let row = 0; row < rows; row++) {
const level = columns[c][row]
ctx.fillStyle = `rgba(${r}, ${g}, ${b}, ${(0.08 + 0.92 * Math.pow(level, 1.25)).toFixed(2)})`
ctx.fillRect(c * (cellW + gap), height - (row + 1) * cellH - row * gap, cellW, cellH)
}
}
}
interface SpectrogramProps {
/** How many columns it holds: the last seconds, the newest on the right. */
columns?: number
/** How many rows: low notes at the bottom. */
rows?: number
/** The track is a friend's: the colour is the friend's. */
friend?: boolean
className?: string
}
/**
* A spectrogram of what is playing, drawn from the sound itself: the last seconds, time running to the right and ending
* now, low notes at the bottom, brighter where there is more energy. It is drawn only while something plays and the page
* is in view, and where the browser cannot listen to the sound it stays empty. It is a picture, with a name.
*/
export default function Spectrogram({ columns = 48, rows = 12, friend = false, className }: SpectrogramProps) {
const { t } = useTranslation()
const canvas = useRef<HTMLCanvasElement>(null)
const playing = usePlayer((s) => s.playing)
const now = usePlayer(currentTrack)
const key = now ? `${now.friend ?? 0}:${now.id}` : ''
useEffect(() => {
const el = canvas.current
if (!el) return
const buffer = new ColumnBuffer(columns, rows)
draw(el, buffer.columns(), rows)
if (!playing) return
const reduced = typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches
const every = reduced ? REDUCED_FRAME_MS : FRAME_MS
let last = 0
let frame = 0
const tick = (at: number) => {
frame = requestAnimationFrame(tick)
if (document.hidden || at - last < every || !hasAnalyser()) return
last = at
const bins = readBins()
if (!bins) return
buffer.push(rowsFromBins(bins, rows))
draw(el, buffer.columns(), rows)
}
frame = requestAnimationFrame(tick)
return () => cancelAnimationFrame(frame)
// A new track starts from an empty picture.
}, [playing, key, columns, rows])
return (
<div role="img" aria-label={t('player.spectrogram')} className={cn(friend ? 'text-friend' : 'text-primary', className)}>
<canvas ref={canvas} aria-hidden="true" className="size-full" />
</div>
)
}