When you visit 'login' page, login.mp3 plays automatically on the page. ("plz enter your phone number~~")
if there's any click event/action on the screen, the music stops playing.
When you move to 'payment' page, payment.mp3 file plays automatically.
if there's any click event/action on the screen, the music stops playing.
However after I refactored the code, 'stop playing music' feature doesn't work. It's supposed to work when I make click event on window. Can you guys help me how I can fix it? Thanks
const LoginPhone = () => {
const domNavigate = useDomNavigate();
const {openKioskAlert} = useContext(KioskAlertContext);
const [phoneNumber, setPhoneNumber] = useState([]);
const [isPlaying, setIsPlaying] = useState(true);
const audioFile = new Audio(`/sounds/hello.mp3`);
// play audio sound
const playSound = () => {
audioFile.play();
};
// stop audio sound
const stopSound = () => {
audioFile.pause();
audioFile.currentTime = 0;
};
useEffect(() => {
playSound();
// when there's click event on window, it stops playing the music
const clickHandler = () => stopSound();
window.addEventListener('click', clickHandler);
return () => window.removeEventListener('click', clickHandler);
}, []);
import {voiceAudio} from '../../src/common/utils/voice';
const LoginPhone = () => {
const domNavigate = useDomNavigate();
const {openKioskAlert} = useContext(KioskAlertContext);
const [phoneNumber, setPhoneNumber] = useState([]);
const {playAudio, stopAudio} = voiceAudio('login-phone');
useEffect(() => {
playAudio();
return () => stopAudio();
}, []);
export const voiceAudio = (title: string) => {
const audioFile = new Audio(`/sounds/${title}.mp3`);
const playAudio = () => audioFile.play();
const stopAudio = () => {
audioFile.pause();
audioFile.currentTime = 0;
};
return {
playAudio,
stopAudio,
};
};
It doesn't work because you are losing a reference to the old audio after assigning a new one. First pause, then assign new sound