Control it with React
Turn the four musical parts into an interactive component. React owns the controls; Strudel owns playback.
You will learn
- Build a pattern from React state
- Start audio with a gesture and update it while playing
- Stop playback and handle errors
Play the component
This is the actual component shown below, playing the same four parts from Layer the parts. Press Play, change the tempo, and untick a part. These checkboxes include or exclude entire parts.
Try changing controls after Stop too: the controls change, but audio waits for another Play.
Keep the controls as plain state
The state has a BPM value and a muted flag for each part. It stores the user’s choices, not an audio engine. The imported LAYERS map contains the reusable drum, bass, chord and melody patterns.
type Part = keyof typeof LAYERS
type Mix = { bpm: number, muted: Record<Part, boolean> }
const PARTS = Object.keys(LAYERS) as Part[]
const INITIAL: Mix = { bpm: 100, muted: { drums: false, bass: false, chords: false, melody: false } }Turn state into a pattern
The builder filters muted parts and stacks the remaining patterns. If everything is muted, it returns silence. It applies the chosen BPM as cpm, with four beats per bar.
This function is independent of React rendering and starts no audio. You can call it from other components too.
// React state in, typed pattern out. A plain function: easy to test, no audio.
const buildPattern = ({ bpm, muted }: Mix) => {
const parts = PARTS.filter((part) => !muted[part]).map((part) => LAYERS[part])
const mix = parts.length > 0 ? fn('stack', parts[0], ...parts.slice(1)) : fn('silence')
return chain(mix, fn('cpm', bpm / 4))
}Choose play, update or stop
Import useStrudel from react-strudel-kit/react. Call play from a click or keyboard gesture; that lets the browser enable audio and loads the runtime on first use.
The change handler stores the next state. Only when status is playing does it call update, replacing the running pattern without restarting its scheduler. Stop cancels pending Play too.
export function ReactMixer() {
const { play, update, stop, status, error } = useStrudel()
const [mix, setMix] = useState(INITIAL)
// Every change rebuilds the pattern. While music plays, update() swaps it in
// without restarting; while stopped, nothing plays until the next Play.
const change = (next: Mix) => {
setMix(next)
if (status === 'playing') void update(buildPattern(next))
}
return (
<div className="react-mixer">
<div className="react-mixer-buttons">
<button className="play-button" onClick={() => void play(buildPattern(mix))}>Play</button>
<button className="stop-button" onClick={stop}>Stop</button>
<output>{status}</output>
</div>
<label>
Tempo: {mix.bpm} BPM
<input type="range" min={70} max={140} value={mix.bpm}
onChange={(event) => change({ ...mix, bpm: Number(event.target.value) })} />
</label>
<div className="react-mixer-parts">
{PARTS.map((part) => (
<label key={part}>
<input type="checkbox" checked={!mix.muted[part]}
onChange={() => change({ ...mix, muted: { ...mix.muted, [part]: !mix.muted[part] } })} />
{part}
</label>
))}
</div>
{error && <p role="alert">{error.message}</p>}
</div>
)
}Recap
- State describes the controls; a pure function describes the pattern.
- Use
playfor an explicit start,updatefor live changes andstopto end playback. - Display the hook’s error and status so failures are visible.
Full ReactMixer component
import { useState } from 'react'
import { chain, fn } from 'react-strudel-kit'
import { useStrudel } from 'react-strudel-kit/react'
import { LAYERS } from './layerASong'
type Part = keyof typeof LAYERS
type Mix = { bpm: number, muted: Record<Part, boolean> }
const PARTS = Object.keys(LAYERS) as Part[]
const INITIAL: Mix = { bpm: 100, muted: { drums: false, bass: false, chords: false, melody: false } }
// React state in, typed pattern out. A plain function: easy to test, no audio.
const buildPattern = ({ bpm, muted }: Mix) => {
const parts = PARTS.filter((part) => !muted[part]).map((part) => LAYERS[part])
const mix = parts.length > 0 ? fn('stack', parts[0], ...parts.slice(1)) : fn('silence')
return chain(mix, fn('cpm', bpm / 4))
}
export function ReactMixer() {
const { play, update, stop, status, error } = useStrudel()
const [mix, setMix] = useState(INITIAL)
// Every change rebuilds the pattern. While music plays, update() swaps it in
// without restarting; while stopped, nothing plays until the next Play.
const change = (next: Mix) => {
setMix(next)
if (status === 'playing') void update(buildPattern(next))
}
return (
<div className="react-mixer">
<div className="react-mixer-buttons">
<button className="play-button" onClick={() => void play(buildPattern(mix))}>Play</button>
<button className="stop-button" onClick={stop}>Stop</button>
<output>{status}</output>
</div>
<label>
Tempo: {mix.bpm} BPM
<input type="range" min={70} max={140} value={mix.bpm}
onChange={(event) => change({ ...mix, bpm: Number(event.target.value) })} />
</label>
<div className="react-mixer-parts">
{PARTS.map((part) => (
<label key={part}>
<input type="checkbox" checked={!mix.muted[part]}
onChange={() => change({ ...mix, muted: { ...mix.muted, [part]: !mix.muted[part] } })} />
{part}
</label>
))}
</div>
{error && <p role="alert">{error.message}</p>}
</div>
)
}
You have built notes, a beat, a bass line, an arrangement and a React player. Explore the API reference or try the Lo-fi loop next.