Master Web Audio API, music loops, effects processing, and mobile audio
Section 1 of 9
// Initialize Web Audio API
const audioContext = new (window.AudioContext || window.webkitAudioContext)();
// Check if audio context is ready
console.log('Sample rate:', audioContext.sampleRate); // Usually 44100 or 48000 Hz
console.log('Current time:', audioContext.currentTime);
// Create a simple audio node
const gainNode = audioContext.createGain();
gainNode.gain.value = 0.5; // 50% volume
gainNode.connect(audioContext.destination); // Connect to speakers
// Best practice: Singleton pattern for audio context
class AudioManager {
constructor() {
this.audioContext = new (window.AudioContext || window.webkitAudioContext)();
this.masterGain = this.audioContext.createGain();
this.masterGain.connect(this.audioContext.destination);
this.masterGain.gain.value = 0.7;
}
getContext() {
return this.audioContext;
}
getMasterGain() {
return this.masterGain;
}
// Resume audio context (needed for user interaction)
async resumeContext() {
if (this.audioContext.state === 'suspended') {
await this.audioContext.resume();
console.log('Audio context resumed');
}
}
}
// Usage
const audioManager = new AudioManager();
audioManager.resumeContext();Create an immersive audio game demonstrating mastery of Web Audio API:
Learn velocity, acceleration, gravity, and realistic physics simulation