PratikWebsite / context /AudioContext.tsx
Keep-Triangle's picture
Upload 35 files
5d33320 verified
Raw History Blame Contribute Delete
10.1 kB
import React, { createContext, useContext, useEffect, useRef, useState } from 'react';
interface AudioContextType {
isMuted: boolean;
toggleMute: () => void;
setSectionAudio: (audioUrl: string | null) => void;
playHoverSound: () => void;
playTickSound: () => void;
}
const AudioContext = createContext<AudioContextType | undefined>(undefined);
// Sound Assets - Using reliable Google Actions Sounds (OGG format supported by most modern browsers)
export const SOUNDS = {
// Fire burning ambience for the "Heat/Drone" feel
AMBIENT_DRONE: "https://actions.google.com/sounds/v1/ambiences/fire.ogg",
// Windy field for Hero section
HERO_WIND: "https://actions.google.com/sounds/v1/weather/windy_field.ogg",
// Market chatter/ambience
MARKET_HUSTLE: "https://actions.google.com/sounds/v1/ambiences/coffee_shop.ogg",
// Texture sound
CRUNCH: "https://actions.google.com/sounds/v1/foley/rhythmic_rocks_crunching.ogg",
// Subtle Switch/Click for UI interactions
UI_HOVER: "https://actions.google.com/sounds/v1/foley/switch_light_04.ogg",
// Mechanical Tick for Loader
LOADER_TICK: "https://actions.google.com/sounds/v1/foley/cassette_tape_button.ogg"
};
export const AudioProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
// Default to FALSE (Sound ON)
const [isMuted, setIsMuted] = useState(false);
// Refs for Audio Elements
const globalAmbientRef = useRef<HTMLAudioElement | null>(null);
const sectionAudioRef = useRef<HTMLAudioElement | null>(null);
const fadeIntervalRef = useRef<number | null>(null);
const resumeOnInteractionCleanupRef = useRef<(() => void) | null>(null);
const setupResumeOnFirstInteraction = (resume: () => void) => {
if (resumeOnInteractionCleanupRef.current) return;
const handler = () => {
resume();
resumeOnInteractionCleanupRef.current?.();
resumeOnInteractionCleanupRef.current = null;
};
window.addEventListener('pointerdown', handler, { once: true });
window.addEventListener('keydown', handler, { once: true });
window.addEventListener('touchstart', handler, { once: true });
resumeOnInteractionCleanupRef.current = () => {
window.removeEventListener('pointerdown', handler);
window.removeEventListener('keydown', handler);
window.removeEventListener('touchstart', handler);
};
};
// Helper: Create Audio with Error Handling
const createSafeAudio = (url: string, loop: boolean = true) => {
try {
const audio = new Audio(url);
audio.loop = loop;
audio.volume = 0;
// Prevent error logging to console if load fails
audio.onerror = (e) => {
console.warn(`Failed to load audio source: ${url}`, e);
};
return audio;
} catch (e) {
console.warn("Audio construction failed", e);
return null;
}
};
// Helper: Fade Volume using a simple interval
const gsapFadeVolume = (audioEl: HTMLAudioElement, targetVolume: number) => {
// Clear any existing fade for this specific requirement if we tracked it per element,
// but for simplicity we rely on the rapid updates.
const step = 0.05;
const fade = setInterval(() => {
if (!audioEl) {
clearInterval(fade);
return;
}
// Check if audio is valid and has volume property
if (typeof audioEl.volume !== 'number') {
clearInterval(fade);
return;
}
if (Math.abs(audioEl.volume - targetVolume) < step) {
audioEl.volume = targetVolume;
clearInterval(fade);
} else if (audioEl.volume < targetVolume) {
audioEl.volume = Math.min(1, audioEl.volume + step);
} else {
audioEl.volume = Math.max(0, audioEl.volume - step);
}
}, 100);
};
// Initialize Global Ambient (The "Base Layer")
useEffect(() => {
const audio = createSafeAudio(SOUNDS.AMBIENT_DRONE);
if (audio) {
globalAmbientRef.current = audio;
// Attempt Auto-play if not muted by default
if (!isMuted) {
const playPromise = audio.play();
if (playPromise !== undefined) {
playPromise
.then(() => {
gsapFadeVolume(audio, 0.4);
})
.catch(e => {
// Browsers block autoplay without interaction.
// Resume on the first user interaction, without surfacing console noise.
setupResumeOnFirstInteraction(() => {
if (!globalAmbientRef.current || isMuted) return;
globalAmbientRef.current
.play()
.then(() => gsapFadeVolume(globalAmbientRef.current!, 0.4))
.catch(() => {
// Ignore subsequent autoplay rejections.
});
});
});
}
}
}
return () => {
if (resumeOnInteractionCleanupRef.current) {
resumeOnInteractionCleanupRef.current();
resumeOnInteractionCleanupRef.current = null;
}
if (globalAmbientRef.current) {
globalAmbientRef.current.pause();
globalAmbientRef.current = null;
}
};
}, []); // Run once on mount
const toggleMute = () => {
const newMutedState = !isMuted;
setIsMuted(newMutedState);
if (!globalAmbientRef.current) return;
if (newMutedState) {
// Mute: Fade out everything
globalAmbientRef.current.pause();
if (sectionAudioRef.current) sectionAudioRef.current.pause();
} else {
// Unmute: Start Ambient
const playPromise = globalAmbientRef.current.play();
if (playPromise !== undefined) {
playPromise
.then(() => {
// Fade in volume to 0.4
gsapFadeVolume(globalAmbientRef.current!, 0.4);
})
.catch(e => console.log("Audio play prevented (Autoplay policy):", e));
}
// Resume section audio if it exists
if (sectionAudioRef.current) {
const sectionPromise = sectionAudioRef.current.play();
if (sectionPromise !== undefined) {
sectionPromise
.then(() => gsapFadeVolume(sectionAudioRef.current!, 0.6))
.catch(e => console.log("Section audio resume prevented:", e));
}
}
}
};
const setSectionAudio = (audioUrl: string | null) => {
if (isMuted) return;
// 1. Handle Existing Section Audio
if (sectionAudioRef.current) {
// Fade out current section audio
const oldAudio = sectionAudioRef.current;
gsapFadeVolume(oldAudio, 0);
setTimeout(() => {
if(oldAudio) {
oldAudio.pause();
// Optional: remove source to free memory if needed
}
}, 1500);
}
// 2. Play New Section Audio (if exists)
if (audioUrl) {
// "Duck" the ambient noise (lower volume)
if (globalAmbientRef.current) gsapFadeVolume(globalAmbientRef.current, 0.1);
const newAudio = createSafeAudio(audioUrl);
if (newAudio) {
sectionAudioRef.current = newAudio;
const playPromise = newAudio.play();
if(playPromise !== undefined) {
playPromise
.then(() => gsapFadeVolume(newAudio, 0.6))
.catch(e => console.warn("Section audio play prevented:", e));
}
}
} else {
// No section audio? Restore ambient volume
if (globalAmbientRef.current) gsapFadeVolume(globalAmbientRef.current, 0.4);
sectionAudioRef.current = null;
}
};
const playHoverSound = () => {
if (isMuted) return;
try {
const audio = new Audio(SOUNDS.UI_HOVER);
audio.volume = 0.15; // Very subtle
audio.play().catch(e => {
// Ignore autoplay errors for interaction sounds
});
} catch (e) {
// Ignore construction errors
}
};
const playTickSound = () => {
if (isMuted) return;
try {
const audio = new Audio(SOUNDS.LOADER_TICK);
audio.volume = 0.25; // Audible but not overwhelming
audio.play().catch(e => {
// Ignore autoplay errors
});
} catch (e) {
// Ignore construction errors
}
};
return (
<AudioContext.Provider value={{ isMuted, toggleMute, setSectionAudio, playHoverSound, playTickSound }}>
{children}
</AudioContext.Provider>
);
};
export const useAudio = () => {
const context = useContext(AudioContext);
if (!context) {
throw new Error('useAudio must be used within an AudioProvider');
}
return context;
};