Home > Blockchain >  I want to play multiple audio files. So I created a function for it. But it can only play one audio.
I want to play multiple audio files. So I created a function for it. But it can only play one audio.

Time:04-19

I'm trying to make voiceAudio as a template so I can play multiple audios if I want. But currently I can play only one audio. If I bring two voiceAudio like I did in example below, one of them wouldn't play.

How can I make it work?!

loginPhone.ts
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,
    };
};

what I would like to do : example

import {voiceAudio} from '../../src/common/utils/voice';

const LoginPhone = () => {
    const domNavigate = useDomNavigate();
    const {openKioskAlert} = useContext(KioskAlertContext);
    const [phoneNumber, setPhoneNumber] = useState([]);

// if I bring bring?!two voiceAudio, one of them wouldn't work..
    const {playAudio, stopAudio} = voiceAudio('login-phone);
    const {playAudio, stopAudio} = voiceAudio('login-pin);


    useEffect(() => {
        playAudio();
        
        return () => stopAudio();
    }, []);

    const play =

CodePudding user response:

The problem may be that you are trying to use the same variable names multiple times. Notice how playAudio and stopAudio are being used twice. This is similar to writing const a = 8; const a = 5.

Try using different names for the second voiceAudio like this:

    const {playAudio, stopAudio} = voiceAudio('login-phone');
    const {playAudio: playAudio2, stopAudio: stopAudio2} = voiceAudio('login-pin');

That will allow you to refer to the playAudio on the second line as playAudio2 and refer to the stopAudio on the second line as stopAudio2.

In your useEffect you should then be able to freely call both functions like this:

    useEffect(() => {
        playAudio();
        playAudio2();
        
        return () => {
           stopAudio();
           stopAudio2();
        }
    }, []);
  • Related