Skip to content

EZ Web Audio / Sampler

Class: Sampler

Defined in: sampler.ts:33

Round-robin playback of multiple sounds.

Sampler holds multiple Sound instances and automatically alternates between them on each play() call. This creates realistic variation when playing repeated samples (e.g., multiple recordings of the same drum hit).

Example

typescript
import { createSampler } from 'ez-web-audio'

// Load multiple kick drum samples for variation
const kick = await createSampler([
  'kick-1.mp3',
  'kick-2.mp3',
  'kick-3.mp3'
])

// Each play() uses the next sample in rotation
kick.play() // plays kick-1
kick.play() // plays kick-2
kick.play() // plays kick-3
kick.play() // back to kick-1

Extended by

Constructors

Constructor

new Sampler(sounds, opts?): Sampler

Defined in: sampler.ts:34

Parameters

sounds

Playable & Connectable[]

opts?

SamplerOptions

Returns

Sampler

Properties

gain

gain: number = 1

Defined in: sampler.ts:49

Gain level applied to each sample when played.

Default

ts
1

name

name: string

Defined in: sampler.ts:43

Optional name to aid in identification.


pan

pan: number = 0

Defined in: sampler.ts:55

Stereo pan position applied to each sample (-1 = left, 0 = center, 1 = right).

Default

ts
0

Methods

getSounds()

getSounds(): readonly Playable & Connectable[]

Defined in: sampler.ts:127

Get a readonly snapshot of the sampler's sounds.

Returns a shallow copy as an array so callers can inspect which sounds are loaded without mutating the internal Set.

Returns

readonly Playable & Connectable[]

Readonly array of sounds in the sampler

Example

typescript
const sampler = await createSampler(['kick-1.mp3', 'kick-2.mp3'])
const sounds = sampler.getSounds()
console.log(sounds.length) // 2

play()

play(): void

Defined in: sampler.ts:79

Play the next sound in the rotation immediately.

Returns

void

Example

typescript
sampler.play() // plays sound 1
sampler.play() // plays sound 2
sampler.play() // plays sound 3 (then wraps to 1)

playAt()

playAt(time): void

Defined in: sampler.ts:108

Play the next sound at a specific AudioContext time.

Parameters

time

number

The AudioContext.currentTime value when to play

Returns

void

Example

typescript
const startTime = audioContext.currentTime + 1
sampler.playAt(startTime) // plays next sound at exactly startTime

playIn()

playIn(seconds): void

Defined in: sampler.ts:93

Play the next sound in the rotation after a delay.

Parameters

seconds

number

Number of seconds from now to play the sound

Returns

void

Example

typescript
sampler.playIn(0.5) // plays next sound in 0.5 seconds