react-native-sound not playing audio at first time

363 Views Asked by At

I'm using react-native-audio package for my game and I want to play an audio for multiple times as function executed. But It's not working perfectly. Here is my code

import Sound from 'react-native-sound';

export default function App(){
    const stepAudio = useRef(null);

    stepAudio.current = new Sound('step.mp3', Sound.MAIN_BUNDLE, (error) => {
    if (error) {
        console.log('Error Step Audio', error);
        return;
    }
    });

    async function movePawnByStep(prevPosition, newPostion, piece, areaIndicator, finished = null) {
        await stepAudio.current.play((success) => {
            if (!success) {
                console.log(success, 'Audio Status');
                stepAudio.current.play();
            }
        });
        piece.position = areaIndicator + ++prevPosition;
        piece.updateTime = Date.now();
        const timeOut = setTimeout(async () => {
            if (prevPosition < newPostion) {
                await movePawnByStep(prevPosition, newPostion, piece, areaIndicator, finished);
                setTestState((prev) => (prev === false ? true : false));
                stepAudio.current.stop();
            } else {
                clearTimeout(timeOut);
                if (finished !== null) {
                    piece.position = FINISHED;
                    piece.updateTime = Date.now();
                }
                setTestState((prev) => !prev);
            }
        }, 100);
        prevPos.current = {};
    }
}

I want the sound to be played every time the function got executed. But It was missing some playbacks.

0

There are 0 best solutions below