Handle play() and load() promises for audio elements

Updated audio playback and preloading logic to check for and handle returned promises from play() and load() methods. This prevents uncaught promise rejections in browsers where these methods may return undefined, improving reliability and error handling for notification sounds.
This commit is contained in:
g
2025-12-09 22:17:20 +00:00
parent e10ad2835e
commit adb01009eb
6 changed files with 70 additions and 51 deletions

View File

@@ -147,21 +147,24 @@ export function NotificationProvider({ children }: NotificationProviderProps) {
const playNotificationSound = () => {
if (audioRef.current) {
audioRef.current.currentTime = 0;
audioRef.current.play().catch(err => {
console.log('Error playing sound:', err);
// Fallback beep if audio file fails
try {
const context = new (window.AudioContext || (window as any).webkitAudioContext)();
const oscillator = context.createOscillator();
oscillator.type = 'sine';
oscillator.frequency.setValueAtTime(800, context.currentTime);
oscillator.connect(context.destination);
oscillator.start();
oscillator.stop(context.currentTime + 0.2);
} catch (e) {
console.error('Could not play fallback audio', e);
}
});
const playPromise = audioRef.current.play();
if (playPromise !== undefined) {
playPromise.catch(err => {
console.log('Error playing sound:', err);
// Fallback beep if audio file fails
try {
const context = new (window.AudioContext || (window as any).webkitAudioContext)();
const oscillator = context.createOscillator();
oscillator.type = 'sine';
oscillator.frequency.setValueAtTime(800, context.currentTime);
oscillator.connect(context.destination);
oscillator.start();
oscillator.stop(context.currentTime + 0.2);
} catch (e) {
console.error('Could not play fallback audio', e);
}
});
}
}
};