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
Sound Synthesis Patterns
Click Sound: Filtered Noise
Short burst of filtered noise for immediate tactile feedback:lib/sounds.ts
- 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
- 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
- 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
- Detuned oscillators: 180 Hz vs 190 Hz (beating effect)
- WaveShaper distortion:
tanhtransfer function - Frequency glide downward
- Lowpass filter at 800 Hz
Audio Graph Patterns
Node Connection Best Practices
- Tab Title
- Tab Title
- Tab Title
Envelope Shaping
Linear vs Exponential Ramps:Performance Considerations
Memory Management
Error Handling
All sound functions wrap Web Audio code in try-catch blocks:- 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
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