Search code examples
reactjsrefactoring

I'm refactoring my code more clean and reusable. However after I refactored the code, one of the functions/features doesn't work


Hey guys, I'm refactoring my code more clean and reusable. Here's what I would like to make.
  • 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.

I hope you guys could understand what I'm trying to make

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


Before Refactored

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);
    }, []);


After Refactored

loginPhone.tsx
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();
    }, []);
utils > voice.ts

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,
    };
};




Solution

  • 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