Spaces:
Running
Running
Download components/studio/Waveform.tsx from Reubencf/Score-Studio: direct link, hf CLI and curl.
- Browser
- Download file 1.54 kB
-
https://huggingface.co/spaces/Reubencf/Score-Studio/resolve/main/components/studio/Waveform.tsx
- Command line
-
hf download hf://spaces/Reubencf/Score-Studio/components/studio/Waveform.tsx
-
curl -L -o Waveform.tsx https://huggingface.co/spaces/Reubencf/Score-Studio/resolve/main/components/studio/Waveform.tsx
1.54 kB
| 'use client'; | |
| import {memo,useEffect,useRef} from 'react'; | |
| import {peaks,peakRate} from '@/lib/studio/audio'; | |
| /** Browsers refuse canvases much wider than this; longer clips are drawn at this width and stretched. */ | |
| const MAX_CANVAS=16000; | |
| /** Draws the visible window of a buffer as a min/max waveform. */ | |
| function Waveform({buffer,offset,duration,width,height,color}:{buffer?:AudioBuffer;offset:number;duration:number;width:number;height:number;color:string}){ | |
| const canvas=useRef<HTMLCanvasElement>(null); | |
| useEffect(()=>{ | |
| const element=canvas.current; | |
| if(!element||!buffer||width<1)return; | |
| const scale=Math.min(window.devicePixelRatio||1,2); | |
| const w=Math.max(1,Math.min(MAX_CANVAS,Math.round(width*scale))),h=Math.max(1,Math.round(height*scale)); | |
| element.width=w;element.height=h; | |
| const draw=element.getContext('2d'); | |
| if(!draw)return; | |
| draw.clearRect(0,0,w,h); | |
| draw.fillStyle=color; | |
| const data=peaks(buffer),rate=peakRate(buffer),blocks=data.length/2,mid=h/2; | |
| for(let x=0;x<w;x++){ | |
| const a=Math.floor((offset+duration*x/w)*rate),b=Math.max(a+1,Math.floor((offset+duration*(x+1)/w)*rate)); | |
| let lo=0,hi=0; | |
| for(let i=Math.max(0,a);i<Math.min(blocks,b);i++){if(data[i*2]<lo)lo=data[i*2];if(data[i*2+1]>hi)hi=data[i*2+1];} | |
| const top=mid-hi*mid*0.95,bottom=mid-lo*mid*0.95; | |
| draw.fillRect(x,top,1,Math.max(1,bottom-top)); | |
| } | |
| },[buffer,offset,duration,width,height,color]); | |
| return <canvas ref={canvas} className="clip-wave" style={{width,height}} aria-hidden="true"/>; | |
| } | |
| export default memo(Waveform); | |