So, when a message comes from socket io, when I say to play the audio, it is outputting the following message
Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first
This is my code:
useEffect(() => {
const handleNewOrder = () => {
audio.play()
};
socketMe?.on("all_orders", handleNewOrder);
return () => socketMe?.off("all_orders", handleNewOrder);
}, [socketMe]);
I fix the problem with hasUserInteracted below, but my code then only emits a sound when I click the button:
import React, { useState, useEffect } from 'react';
function MyComponent() {
const = useState(new Audio('your-audio-file.mp3')); // Preload audio
const [hasUserInteracted, setHasUserInteracted] = useState(false);
const [pendingEventData, setPendingEventData] = useState(null);
useEffect(() => {
const handleNewOrder = (data) => {
if (hasUserInteracted) {
audio.play(); // Play audio immediately if user interacted
} else {
setPendingEventData(data); // Store event data for later
}
};
socketMe?.on("all_orders", handleNewOrder);
return () => socketMe?.off("all_orders", handleNewOrder);
}, [socketMe, hasUserInteracted, audio]);
const handleUserInteraction = () => {
setHasUserInteracted(true);
if (pendingEventData) {
audio.play(); // Play audio if pending event data exists
setPendingEventData(null); // Clear pending data
}
};
return (
<div>
<button onClick={handleUserInteraction}>Click to Enable Sounds</button>
</div>
);
}
**I need it to sound when a new message (i.e. order) arrives, not when a button is pressed. Can anyone help with this problem?
**