EZ Web Audio / Track
Class: Track
Defined in: track.ts:37
Music track with position tracking, pause/resume, and seeking.
Track extends Sound with playback position awareness. Use Track for longer audio files where users need to pause, resume, or seek to specific positions. Each Track can only play once at a time (unlike Sound which allows overlap).
Example
import { createTrack } from 'ez-web-audio'
const track = await createTrack('song.mp3')
track.play()
// Pause and resume
track.pause()
track.resume()
// Seek to 30 seconds
track.seek(30).as('seconds')
// Get current position
console.log(track.position)
// { raw: 30.5, string: '0:30', pojo: { minutes: 0, seconds: 30 } }
// Check playback state
console.log(track.isPlaying) // true
console.log(track.percentPlayed) // 15.5Extends
Constructors
Constructor
new Track(
audioContext,audioBuffer,opts?):Track
Defined in: sound.ts:48
Create a Sound instance.
Note: Use createSound factory function instead of calling this directly.
Parameters
audioContext
AudioContext
The AudioContext to use for audio operations
audioBuffer
AudioBuffer
The decoded audio data to play
opts?
any
Optional configuration (name, setTimeout override)
Returns
Track
Inherited from
Properties
_analyzer
protected_analyzer:Analyzer|null=null
Defined in: base-sound.ts:114
Inherited from
_destination
protected_destination:AudioNode
Defined in: base-sound.ts:107
Inherited from
_isPlaying
protected_isPlaying:boolean=false
Defined in: base-sound.ts:70
Inherited from
audioContext
audioContext:
AudioContext
Defined in: base-sound.ts:165
Inherited from
audioSourceNode
audioSourceNode:
AudioBufferSourceNode
Defined in: sound.ts:34
The underlying AudioBufferSourceNode that plays the audio.
Inherited from
controller
protectedcontroller:SoundController
Defined in: sound.ts:37
Controller for managing gain, pan, and other audio parameters.
Inherited from
debug?
optionaldebug:boolean
Defined in: base-sound.ts:163
Default
undefined (follows global debug mode)Example
sound.debug = true // enable debug for this sound
sound.debug = false // silence this sound even when global debug is onInherited from
effectChainInput
protectedeffectChainInput:GainNode
Defined in: base-sound.ts:100
Inherited from
effects
protectedeffects:Effect[] =[]
Defined in: base-sound.ts:93
Inherited from
gainNode
protectedgainNode:GainNode
Defined in: base-sound.ts:78
The GainNode controlling this sound's volume.
For simple volume control, use changeGainTo() or update('gain'). For advanced routing, use getGainNode().
Inherited from
name
name:
string
Defined in: base-sound.ts:149
Inherited from
pannerNode
protectedpannerNode:StereoPannerNode
Defined in: base-sound.ts:80
Inherited from
setTimeout()
protectedsetTimeout: (fn,delayMillis) =>number
Defined in: base-sound.ts:81
Parameters
fn
() => void
delayMillis
number
Returns
number
Inherited from
startedPlayingAt
protectedstartedPlayingAt:number=0
Defined in: base-sound.ts:82
Inherited from
startOffset
protectedstartOffset:number=0
Defined in: base-sound.ts:123
Offset in seconds from the beginning of the audio buffer where playback starts. Used internally by Track for seek/resume functionality.
Default
0See
https://developer.mozilla.org/en-US/docs/Web/API/AudioScheduledSourceNode/start
Inherited from
Accessors
duration
Get Signature
get duration():
TimeObject
Defined in: sound.ts:124
Get the duration of the audio buffer.
Returns a TimeObject with the duration in multiple formats:
raw: Duration in secondsstring: Formatted as 'MM:SS'pojo: Object withminutesandsecondsproperties
Example
const sound = await createSound('song.mp3')
console.log(sound.duration.raw) // 180.5
console.log(sound.duration.string) // '3:00'
console.log(sound.duration.pojo) // { minutes: 3, seconds: 0 }Returns
TimeObject
Inherited from
isPlaying
Get Signature
get isPlaying():
boolean
Defined in: base-sound.ts:1082
Whether the sound is currently playing.
Example
if (sound.isPlaying) {
await sound.stop()
}Returns
boolean
Inherited from
percentGain
Get Signature
get percentGain():
number
Defined in: base-sound.ts:1094
Current gain as a percentage (0-100).
Example
console.log(`Volume: ${sound.percentGain}%`) // "Volume: 50%"Returns
number
Inherited from
percentPlayed
Get Signature
get percentPlayed():
number
Defined in: track.ts:79
Get the current playback position as a percentage (0-100).
Example
const track = await createTrack('song.mp3')
track.play()
// Use for progress bar
progressBar.style.width = `${track.percentPlayed}%`Returns
number
position
Get Signature
get position():
TimeObject
Defined in: track.ts:60
Get the current playback position.
Returns a TimeObject with the position in multiple formats:
raw: Position in secondsstring: Formatted as 'MM:SS'pojo: Object withminutesandsecondsproperties
Example
const track = await createTrack('song.mp3')
track.play()
// After playing for a while
console.log(track.position.raw) // 65.5
console.log(track.position.string) // '1:05'
console.log(track.position.pojo) // { minutes: 1, seconds: 5 }Returns
TimeObject
Methods
_onPlaybackStarted()
protected_onPlaybackStarted():void
Defined in: track.ts:89
Hook called after playback starts. Sets up the onended handler and starts position tracking.
Returns
void
Overrides
addEffect()
addEffect(
effect,position?):this
Defined in: base-sound.ts:344
Add an effect to the effect chain. Effects persist across multiple play() calls.
Parameters
effect
The Effect instance to add
position?
number
Optional index to insert at (defaults to end of chain)
Returns
this
this for chaining
Example
const filter = createFilterEffect(audioContext, 'lowpass', { frequency: 1000 })
sound.addEffect(filter)Inherited from
addEffects()
addEffects(
effects,position?):this
Defined in: base-sound.ts:414
Add multiple effects to the effect chain in one call. The chain is rewired only once after all effects are added, which is more efficient than calling addEffect() multiple times.
Parameters
effects
Effect[]
Array of Effect instances to add
position?
number
Optional index to insert at (defaults to end of chain)
Returns
this
this for chaining
Example
const filter = createFilterEffect('lowpass', { frequency: 800 })
const boost = createGainEffect(1.5)
sound.addEffects([filter, boost])Inherited from
addEventListener()
Call Signature
addEventListener<
K>(type,listener,options?):void
Defined in: base-sound.ts:555
Add a typed event listener for sound lifecycle events. Overloaded to provide type safety for known event types while remaining compatible with EventTarget.
Type Parameters
K
K extends keyof SoundEventMap
Parameters
type
K
The event type ('play', 'stop', 'end', etc.)
listener
(event) => void
The event handler function
options?
Standard addEventListener options
boolean | AddEventListenerOptions
Returns
void
Inherited from
Call Signature
addEventListener(
type,listener,options?):void
Defined in: base-sound.ts:560
Add a typed event listener for sound lifecycle events. Overloaded to provide type safety for known event types while remaining compatible with EventTarget.
Parameters
type
string
The event type ('play', 'stop', 'end', etc.)
listener
The event handler function
EventListenerOrEventListenerObject | null
options?
Standard addEventListener options
boolean | AddEventListenerOptions
Returns
void
Inherited from
changeGainTo()
changeGainTo(
value):this
Defined in: base-sound.ts:750
Set the gain (volume) immediately.
Convenience method for update('gain').to(value).as('ratio').
Parameters
value
number
Gain from 0 (silent) to 1 (full volume)
Returns
this
this for chaining
Example
sound.changeGainTo(0.5) // Half volume
sound.changeGainTo(0) // Muted
sound.changeGainTo(1) // Full volumeInherited from
changePanTo()
changePanTo(
value):this
Defined in: base-sound.ts:730
Set the pan position immediately.
Convenience method for update('pan').to(value).as('ratio').
Parameters
value
number
Pan position from -1 (left) to 1 (right), 0 is center
Returns
this
this for chaining
Example
sound.changePanTo(-1) // Hard left
sound.changePanTo(0) // Center
sound.changePanTo(1) // Hard rightInherited from
emit()
protectedemit<K>(type,detail):void
Defined in: base-sound.ts:606
Emit a typed event with the given detail.
Type Parameters
K
K extends keyof SoundEventMap
Parameters
type
K
The event type to emit
detail
SoundEventMap[K]["detail"]
The event detail object
Returns
void
Inherited from
getAnalyzer()
getAnalyzer():
Analyzer|null
Defined in: base-sound.ts:521
Get the currently attached analyzer, if any.
Returns
Analyzer | null
The attached Analyzer instance, or null if none attached
Inherited from
getEffects()
getEffects(): readonly
Effect[]
Defined in: base-sound.ts:457
Get a readonly copy of the current effects array.
Returns
readonly Effect[]
Shallow copy of the effects array
Inherited from
getGainNode()
getGainNode():
GainNode
Defined in: base-sound.ts:540
Get the GainNode for this sound.
Provides controlled access to the underlying GainNode for advanced audio routing scenarios (e.g., crossfading between tracks). For simple volume control, use changeGainTo() or update('gain').
Returns
GainNode
The GainNode controlling this sound's volume
Example
const node = sound.getGainNode()
node.gain.linearRampToValueAtTime(0, ctx.currentTime + 2)Inherited from
later()
protectedlater(fn):void
Defined in: base-sound.ts:1098
Parameters
fn
() => void
Returns
void
Inherited from
off()
off<
K>(type,listener):this
Defined in: base-sound.ts:681
Unsubscribe from an event.
Note: Due to native EventTarget limitations, you must provide the same listener function reference that was used when subscribing. To remove listeners, store the function reference when adding it.
Type Parameters
K
K extends keyof SoundEventMap
Parameters
type
K
The event type to unsubscribe from
listener
(event) => void
The event handler function to remove
Returns
this
this for chaining
Example
const handler = (e) => console.log(e.detail);
sound.on('play', handler);
// later...
sound.off('play', handler);Inherited from
on()
on<
K>(type,listener):this
Defined in: base-sound.ts:629
Subscribe to one or more events. Supports chaining.
Type Parameters
K
K extends keyof SoundEventMap
Parameters
type
The event type(s) to subscribe to
K | K[]
listener
(event) => void
The event handler function
Returns
this
this for chaining
Example
sound.on('play', handlePlay).on('stop', handleStop);
sound.on(['play', 'stop'], handleBoth);Inherited from
once()
once<
K>(type,listener):this
Defined in: base-sound.ts:654
Subscribe to an event once. Handler is removed after first invocation.
Type Parameters
K
K extends keyof SoundEventMap
Parameters
type
K
The event type to subscribe to
listener
(event) => void
The event handler function
Returns
this
this for chaining
Example
sound.once('end', () => console.log('Playback finished'));Inherited from
onPlayRamp()
onPlayRamp(
type,rampType?):object
Defined in: base-sound.ts:812
Schedule a parameter ramp when play() is called.
Use this for smooth transitions like vibrato, tremolo, or automation.
Parameters
type
The parameter to ramp ('gain' or 'pan')
rampType?
RampType
Type of ramp curve ('linear' or 'exponential')
Returns
object
Fluent builder for setting start value, end value, and duration
from()
from: (
startValue) =>object
Parameters
startValue
number
Returns
object
to()
to: (
endValue) =>object
Parameters
endValue
number
Returns
object
in()
in: (
endTime) =>void
Parameters
endTime
number
Returns
void
Example
// Fade out over 2 seconds
sound.onPlayRamp('gain', 'linear').from(1).to(0).in(2)
sound.play()
// Pan sweep from left to right over 4 seconds
sound.onPlayRamp('pan', 'linear').from(-1).to(1).in(4)
sound.play()Inherited from
onPlaySet()
onPlaySet(
type):object
Defined in: base-sound.ts:783
Schedule a parameter value to be set when play() is called.
Use this for fade-ins, fade-outs, or precise parameter timing. The value is applied relative to when play() is called.
Parameters
type
The parameter to control ('gain' or 'pan')
Returns
object
Fluent builder for setting value and timing
to()
to: (
value) =>object
Parameters
value
number
Returns
object
at()
at: (
time) =>void
Parameters
time
number
Returns
void
endingAt()
endingAt: (
time,rampType?) =>void
Parameters
time
number
rampType?
RampType
Returns
void
Example
// Fade in: start at 0, ramp to 1 over 0.5 seconds
sound.onPlaySet('gain').to(0).at(0)
sound.onPlaySet('gain').to(1).endingAt(0.5, 'linear')
sound.play()
// Start panned left, move to center over 2 seconds
sound.onPlaySet('pan').to(-1).at(0)
sound.onPlaySet('pan').to(0).endingAt(2, 'linear')
sound.play()Inherited from
pause()
pause():
void
Defined in: track.ts:114
Pause playback at the current position.
The track remembers its position so it can be resumed later. Emits a 'pause' event with the current playback position.
Returns
void
Example
const track = await createTrack('song.mp3')
track.play()
// Pause after 5 seconds
setTimeout(() => track.pause(), 5000)
// Listen for pause events
track.on('pause', (e) => {
console.log('Paused at', e.detail.position)
})play()
play():
Promise<void>
Defined in: base-sound.ts:837
Play the sound immediately.
Resumes the AudioContext if suspended, sets up the audio source, and starts playback. For finite-duration sounds (Sound, Track), automatically schedules an 'end' event when playback completes.
Returns
Promise<void>
Promise that resolves when playback begins
Example
const sound = await createSound('click.mp3')
await sound.play()Inherited from
playAt()
playAt(
time):Promise<void>
Defined in: base-sound.ts:913
Play the audio source at a specific time.
This is the underlying method for all play variants. Time is measured in seconds from when the AudioContext was created (audioContext.currentTime).
Parameters
time
number
The AudioContext time when playback should start
Returns
Promise<void>
Example
// Play immediately
sound.playAt(audioContext.currentTime)
// Play in 2 seconds
sound.playAt(audioContext.currentTime + 2)
// Sync multiple sounds
const startTime = audioContext.currentTime + 0.1
sound1.playAt(startTime)
sound2.playAt(startTime)Inherited from
playFor()
playFor(
duration):void
Defined in: base-sound.ts:867
Play for a specific duration, then stop automatically.
Parameters
duration
number
Seconds of playback before stopping
Returns
void
Example
// Play for 3 seconds
sound.playFor(3)Inherited from
playIn()
playIn(
when):void
Defined in: base-sound.ts:852
Schedule playback after a delay.
Parameters
when
number
Seconds from now until playback starts
Returns
void
Example
// Play in 2 seconds
sound.playIn(2)Inherited from
playInAndStopAfter()
playInAndStopAfter(
playIn,stopAfter):void
Defined in: base-sound.ts:886
Play after a delay, then stop after a duration.
Combines playIn() and stopIn() for precise timed playback.
Parameters
playIn
number
Seconds from now until playback starts
stopAfter
number
Seconds of playback before stopping (from play start)
Returns
void
Example
// Start in 1 second, play for 3 seconds
sound.playInAndStopAfter(1, 3)Inherited from
removeEffect()
removeEffect(
effect):this
Defined in: base-sound.ts:378
Remove an effect from the effect chain.
Parameters
effect
The Effect instance to remove
Returns
this
this for chaining
Example
sound.removeEffect(filter)Inherited from
removeEventListener()
Call Signature
removeEventListener<
K>(type,listener,options?):void
Defined in: base-sound.ts:582
Remove a typed event listener for sound lifecycle events. Overloaded to provide type safety for known event types while remaining compatible with EventTarget.
Type Parameters
K
K extends keyof SoundEventMap
Parameters
type
K
The event type ('play', 'stop', 'end', etc.)
listener
(event) => void
The event handler function to remove
options?
Standard removeEventListener options
boolean | EventListenerOptions
Returns
void
Inherited from
Call Signature
removeEventListener(
type,listener,options?):void
Defined in: base-sound.ts:587
Remove a typed event listener for sound lifecycle events. Overloaded to provide type safety for known event types while remaining compatible with EventTarget.
Parameters
type
string
The event type ('play', 'stop', 'end', etc.)
listener
The event handler function to remove
EventListenerOrEventListenerObject | null
options?
Standard removeEventListener options
boolean | EventListenerOptions
Returns
void
Inherited from
resume()
resume():
void
Defined in: track.ts:160
Resume playback from the paused position.
If the track was paused, resumes from where it left off. Emits a 'resume' event with the playback position.
Returns
void
Example
const track = await createTrack('song.mp3')
track.play()
track.pause()
// Resume later
track.resume()
// Listen for resume events
track.on('resume', (e) => {
console.log('Resumed at', e.detail.position)
})rewireEffects()
rewireEffects():
void
Defined in: base-sound.ts:483
Re-wire the effect chain. Call this after toggling effect.bypass to update the audio routing.
Returns
void
Inherited from
seek()
seek(
amount):object
Defined in: track.ts:256
Seek to a specific position in the track.
Returns a fluent builder with .as(type) to specify the unit of the value:
'seconds': Absolute position in seconds'percent': Percentage of total duration (0-100)'ratio': Ratio of total duration (0-1)'inverseRatio': Distance from end as ratio (0 = end, 1 = start)
Emits a 'seek' event with the new and previous positions.
Parameters
amount
number
The position value (meaning depends on the .as() type)
Returns
object
Fluent builder with .as(type) method
as()
as: (
type) =>void
Parameters
type
SeekType
Returns
void
Example
const track = await createTrack('song.mp3')
// For a track with 100 second duration, all of these seek to 90 seconds:
track.seek(90).as('seconds')
track.seek(90).as('percent')
track.seek(0.9).as('ratio')
track.seek(0.1).as('inverseRatio')
// Listen for seek events
track.on('seek', (e) => {
console.log('Seeked from', e.detail.previousPosition, 'to', e.detail.position)
})setAnalyzer()
setAnalyzer(
analyzer):this
Defined in: base-sound.ts:510
Attach an analyzer to this sound for visualization. The analyzer is inserted at the end of the signal chain (after effects and panner, before destination), showing the fully processed signal.
The analyzer is a passthrough node - audio flows through it unchanged while providing frequency and waveform data for visualization.
Parameters
analyzer
The Analyzer instance to attach, or null to detach
Analyzer | null
Returns
this
this for chaining
Example
const analyzer = createAnalyzer(audioContext, { fftSize: 2048 })
sound.setAnalyzer(analyzer)
function draw() {
const freqData = analyzer.getFrequencyData()
// Draw frequency bars
requestAnimationFrame(draw)
}Inherited from
setDestination()
setDestination(
node):this
Defined in: base-sound.ts:473
Set a custom destination for audio output instead of audioContext.destination. Useful for routing to sub-mixes, analyzers, or other processing chains.
Parameters
node
AudioNode
The AudioNode to route output to
Returns
this
this for chaining
Example
const analyzer = audioContext.createAnalyser()
analyzer.connect(audioContext.destination)
sound.setDestination(analyzer)Inherited from
setup()
protectedsetup():void
Defined in: sound.ts:65
Set up a new AudioBufferSourceNode for playback. Called automatically before each play() - creates fresh source nodes since AudioBufferSourceNode is single-use.
Returns
void
Inherited from
stop()
stop():
Promise<void>
Defined in: track.ts:190
Stop playback and reset position to the beginning.
Unlike pause(), stop() resets the playback position to 0. The next play() will start from the beginning.
Returns
Promise<void>
Example
const track = await createTrack('song.mp3')
track.play()
// Stop and reset
await track.stop()
console.log(track.position.raw) // 0Overrides
stopAt()
stopAt(
time):Promise<void>
Defined in: base-sound.ts:1023
Stop the audio source at a specific time.
This is the underlying method for all stop variants. Time is measured in seconds from when the AudioContext was created (audioContext.currentTime).
Parameters
time
number
The AudioContext time when playback should stop
Returns
Promise<void>
Example
// Stop immediately
sound.stopAt(audioContext.currentTime)
// Stop in 5 seconds
sound.stopAt(audioContext.currentTime + 5)Inherited from
stopIn()
stopIn(
seconds):Promise<void>
Defined in: base-sound.ts:1002
Stop the audio source after a delay.
Parameters
seconds
number
Seconds from now until playback stops
Returns
Promise<void>
Example
sound.play()
// Stop after 5 seconds
sound.stopIn(5)Inherited from
update()
update(
type):object
Defined in: base-sound.ts:707
Update an audio parameter immediately.
Returns a fluent builder for setting the parameter value. Use .to(value) to set the value, then .as(unit) for unit interpretation.
Parameters
type
The parameter to update ('gain' or 'pan')
Returns
object
Fluent builder for setting the value
to()
to: (
value) =>object
Parameters
value
number
Returns
object
as()
as: (
method) =>void
Parameters
method
RatioType
Returns
void
Example
// Set gain to 50%
sound.update('gain').to(0.5).as('ratio')
// Set pan to left
sound.update('pan').to(-1).as('ratio')Inherited from
wireConnections()
protectedwireConnections():void
Defined in: sound.ts:102
Wire audio source to the effect chain input.
Returns
void