{"spec_id":"waveform-audio","library":"muix","language":"javascript","code":"// anyplot.ai\n// waveform-audio: Audio Waveform Plot\n// Library: muix 9.17.0 | JavaScript 22.23.4\n// Quality: 87/100 | Updated: 2026-11-08\nimport { LineChart } from \"@mui/x-charts/LineChart\";\nimport { ChartsReferenceLine } from \"@mui/x-charts/ChartsReferenceLine\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst FULL_SCALE = 1; // normalized amplitude spans -1 to +1\n// Min/max envelope buckets across the plot width: few enough that each bucket\n// spans a full cycle of the tone, so its maximum is a true peak, and the\n// outline follows the peaks instead of zigzagging between cycle phases.\nconst BUCKETS = 300;\nconst TITLE = \"waveform-audio · javascript · muix · anyplot.ai\";\nconst TITLE_H = 80;\n\n// Columns: set these to your data's column names\nconst TIME = \"Time (s)\"; // role: time\nconst AMPLITUDE = \"Amplitude (normalized)\"; // role: amplitude\n\n// Data: replace this block with your own records, one object per row\n// A simulated spoken utterance, 2 s at 22.05 kHz: a 180 Hz fundamental with\n// two harmonics, shaped by six overlapping syllable envelopes plus a little\n// breath noise.\nconst data = (() => {\n  let state = 42;\n  const rand = () => {\n    state = (state * 1103515245 + 12345) % 2147483648;\n    return state / 2147483648;\n  };\n  const rate = 22050;\n  const count = Math.round(rate * 2.0);\n  const f0 = 180;\n  const syllables = [0.22, 0.5, 0.86, 1.18, 1.5, 1.78];\n  const envelopeAt = (time) => syllables.reduce((sum, c) => sum + Math.exp(-0.5 * ((time - c) / 0.13) ** 2), 0);\n  let peak = 0;\n  for (let i = 0; i < count; i += 1) peak = Math.max(peak, envelopeAt(i / rate));\n  return Array.from({ length: count }, (_, i) => {\n    const time = i / rate;\n    const envelope = envelopeAt(time) / peak;\n    const tone =\n      Math.sin(2 * Math.PI * f0 * time) +\n      0.5 * Math.sin(2 * Math.PI * f0 * 2 * time) +\n      0.25 * Math.sin(2 * Math.PI * f0 * 3 * time);\n    const breath = (rand() - 0.5) * 0.07 * envelope;\n    return { [TIME]: Math.round(time * 1e6) / 1e6, [AMPLITUDE]: Math.round((envelope * (tone / 1.75) + breath) * 1e4) / 1e4 };\n  });\n})();\n\n// Plot: reads only data and the constants above\nconst samples = data\n  .filter((d) => d[TIME] != null && d[AMPLITUDE] != null)\n  .sort((a, b) => a[TIME] - b[TIME]);\n\n// Min/max envelope: each bucket keeps the highest and lowest sample it holds,\n// so every peak survives the reduction to the plot width without aliasing.\nconst bucketSize = Math.ceil(samples.length / BUCKETS);\nconst bucketTimes = [];\nconst upper = [];\nconst lower = [];\nfor (let start = 0; start < samples.length; start += bucketSize) {\n  const bucket = samples.slice(start, start + bucketSize).map((d) => d[AMPLITUDE]);\n  bucketTimes.push((samples[start][TIME] + samples[start + bucket.length - 1][TIME]) / 2);\n  upper.push(Math.max(...bucket));\n  lower.push(Math.min(...bucket));\n}\n\n// Focal point: the bucket with the largest absolute excursion\nconst peakIndex = upper.reduce((best, v, i) => (Math.max(v, -lower[i]) > Math.max(upper[best], -lower[best]) ? i : best), 0);\nconst peakValue = Math.max(upper[peakIndex], -lower[peakIndex]);\nconst peakSigned = upper[peakIndex] === peakValue ? upper[peakIndex] : lower[peakIndex];\nconst tStart = samples[0][TIME];\nconst tEnd = samples[samples.length - 1][TIME];\nconst duration = tEnd - tStart;\nconst TIME_UNIT = TIME.match(/\\(([^)]+)\\)\\s*$/)?.[1] ?? \"\";\nconst SUBTITLE = `${samples.length.toLocaleString(\"en-US\")} samples over ${duration.toFixed(2)} ${TIME_UNIT} · drawn as a min/max envelope of ${upper.length} buckets`;\n\nexport default function Chart() {\n  const { width, height } = window.ANYPLOT_SIZE;\n\n  return (\n    <div style={{ width, height, background: t.pageBg, display: \"flex\", flexDirection: \"column\" }}>\n      <div style={{ height: TITLE_H, padding: \"18px 36px 0\", boxSizing: \"border-box\" }}>\n        <div style={{ fontSize: 22, fontWeight: 600, color: t.ink, lineHeight: 1.2 }}>{TITLE}</div>\n        <div style={{ fontSize: 15, color: t.inkSoft, lineHeight: 1.2, marginTop: 8 }}>{SUBTITLE}</div>\n      </div>\n      <LineChart\n        width={width}\n        height={height - TITLE_H}\n        skipAnimation\n        hideLegend\n        margin={{ top: 28, right: 48, bottom: 12, left: 24 }}\n        grid={{ horizontal: true, vertical: true }}\n        xAxis={[\n          {\n            data: bucketTimes,\n            scaleType: \"linear\",\n            min: tStart,\n            max: tEnd,\n            label: TIME,\n            valueFormatter: (v) => v.toFixed(2),\n            tickNumber: 10,\n            height: 72,\n            labelStyle: { fontSize: 16, fill: t.ink },\n            tickLabelStyle: { fontSize: 15, fill: t.inkSoft },\n          },\n        ]}\n        yAxis={[\n          {\n            min: -FULL_SCALE,\n            max: FULL_SCALE,\n            label: AMPLITUDE,\n            valueFormatter: (v) => v.toFixed(1),\n            width: 80,\n            labelStyle: { fontSize: 16, fill: t.ink },\n            tickLabelStyle: { fontSize: 15, fill: t.inkSoft },\n          },\n        ]}\n        series={[\n          {\n            id: \"upper\",\n            data: upper,\n            area: true,\n            showMark: ({ index }) => index === peakIndex && upper[index] === peakValue,\n            shape: \"circle\",\n            curve: \"linear\",\n            color: t.palette[0],\n            label: AMPLITUDE,\n          },\n          {\n            id: \"lower\",\n            data: lower,\n            area: true,\n            showMark: ({ index }) => index === peakIndex && -lower[index] === peakValue,\n            shape: \"circle\",\n            curve: \"linear\",\n            color: t.palette[0],\n          },\n        ]}\n        sx={{\n          \"& .MuiLineChart-area\": { fillOpacity: 0.5 },\n          \"& .MuiLineChart-line\": { strokeWidth: 1.25 },\n          \"& .MuiLineChart-mark\": { fill: t.ink, stroke: t.pageBg, strokeWidth: 2 },\n          \"& .MuiChartsGrid-line\": { stroke: t.grid },\n          \"& .MuiChartsAxis-line\": { stroke: t.inkSoft },\n          \"& .MuiChartsAxis-tick\": { stroke: t.inkSoft },\n        }}\n      >\n        <ChartsReferenceLine y={0} lineStyle={{ stroke: t.ink, strokeWidth: 1.5, opacity: 0.75 }} />\n        <ChartsReferenceLine\n          x={bucketTimes[peakIndex]}\n          label={`Largest excursion ${peakSigned.toFixed(2)}`}\n          labelAlign={peakSigned < 0 ? \"end\" : \"start\"}\n          spacing={{ x: 8, y: 6 }}\n          labelStyle={{ fontSize: 15, fill: t.inkSoft }}\n          lineStyle={{ stroke: t.inkSoft, strokeWidth: 1.25, strokeDasharray: \"5 5\" }}\n        />\n      </LineChart>\n    </div>\n  );\n}\n"}