Skip to main content

Web Audio API Implementation

This guide explores the production Web Audio API implementation used throughout the User Interface Wiki for procedural sound generation. All sound effects are synthesized in real-time using oscillators, noise generators, and audio processing nodes.

Architecture

AudioContext Management

The implementation uses a singleton pattern to manage the AudioContext lifecycle:
lib/sounds.ts
The AudioContext may be suspended by browser autoplay policies. Always resume the context on user interaction.

Sound Synthesis Patterns

Click Sound: Filtered Noise

Short burst of filtered noise for immediate tactile feedback:
lib/sounds.ts
Key Techniques:
  • Exponential decay envelope: Math.exp(-i / 50)
  • Random frequency variation: 4000 + Math.random() * 1000
  • Short duration: 8ms buffer

Pop Sound: Frequency Sweep

Smooth frequency glide for non-destructive feedback:
lib/sounds.ts
Parameters:
  • Start frequency: 400 Hz
  • End frequency: 150 Hz
  • Duration: 50ms
  • Envelope: Exponential decay

Success Sound: Arpeggio Sequence

Musical phrase conveying positive outcome:
lib/sounds.ts
Musical Structure:
  • Notes: C major triad (C5, E5, G5)
  • Timing: 80ms spacing between notes
  • Harmonics: Fundamental + octave doubling
  • Finish: High shimmer at C6

Error Sound: Distorted Dissonance

Harsh tone conveying failure:
lib/sounds.ts
Dissonance Techniques:
  • Detuned oscillators: 180 Hz vs 190 Hz (beating effect)
  • WaveShaper distortion: tanh transfer function
  • Frequency glide downward
  • Lowpass filter at 800 Hz

Audio Graph Patterns

Node Connection Best Practices

Envelope Shaping

Linear vs Exponential Ramps:
Exponential ramps cannot reach zero. Use 0.001 as the target value instead.
Attack-Decay-Sustain-Release (ADSR):

Performance Considerations

Memory Management

Error Handling

All sound functions wrap Web Audio code in try-catch blocks:
Rationale:
  • Browsers may not support Web Audio
  • AudioContext may fail to resume
  • Sounds should never break functionality

Buffer Generation

Integration with React

Button Component

components/button/index.tsx

Context-Specific Sounds

Browser Compatibility

Safari requires user gesture to unlock AudioContext. The implementation automatically resumes suspended contexts on first interaction.
All major browsers support Web Audio API:
  • Chrome/Edge: Full support
  • Firefox: Full support
  • Safari: Full support (requires gesture unlock)
  • Mobile browsers: Full support

Advanced Techniques

Frequency Randomization

Add subtle variation to prevent repetition fatigue:

Gain Randomization

Simulate natural variation in interaction force:

Noise Envelopes

Reference

Filter Types

Oscillator Types

Timing Guidelines

Next Steps

Motion Implementation

Explore advanced animation patterns with Motion

Performance Optimization

Learn bundle size and runtime optimization techniques