简体   繁体   中英

How to check the current time of song and make the countdown of it JS React?

I am writing the app, where there will be some audio files. User presses the button, audio starts and counter appears (the current time of song beggining with 00:00).

When user presses again, song and timer stops. My problem, I cannot stop timer. I used constructor new Audio and its methods. But I dont understand how it is better to follow the current time of song and make.


function App() {

    const audioTune = new Audio(alarm);

    const [isPlaying, setPlayingAudio] = useState(false)
    const [durationOfSong, setDurationOfSong] = useState<any>()
    const [currentTime, setCurrentTime] = useState<number>(0)


    /* инициализация и длина песни */
    useEffect(()=>{audioTune.load(); setTimeout(()=>setDurationOfSong(audioTune.duration), 1000)}, [])

    const audioRef = useRef(audioTune);

/* Получаем время песни */
    var minutes = Math.floor(durationOfSong / 60);
    var seconds = durationOfSong - minutes * 60;
    function str_pad_left(string:any,pad:any,length:any) {
        return (new Array(length+1).join(pad)+string).slice(-length);
    }
    var finalTime = str_pad_left(minutes,'0',2)+':'+str_pad_left(seconds,'0',2);

    /* Здесь попытка создать таймер, но нет идей как его в нужный момент зачистить */

    let song = () => {
        let playingSong = setInterval(()=>setCurrentTime((prev:any)=>prev+1), 1000)
    }

    /* включение выключение песни */

    useEffect(() => {
        if (isPlaying) {
            audioRef.current.play();
            song()
        } else {
            audioRef.current.pause()
        }
    }, [isPlaying]);

    return (
        <div className="App">
            <h3 className="mb-4">Play an mp3 file</h3>
            <button style={{backgroundColor:"green"}} onClick={()=>setPlayingAudio(true)}>start</button>
            <button style={{backgroundColor:"red"}} onClick={()=>setPlayingAudio(false)}>stop</button>
            <p>{currentTime}:Current time</p>
            <p>{!isNaN(durationOfSong) && finalTime}</p>
        </div>
    );
}

You can get the current time from the Audio element itself using .currentTime ; in your React, I guess it would be either audioTune.currentTime or audioRef.current.currentTime (I am not that great at Reacting). .currentTime will always be correct, you just need to set up an interval in an effect to keep displaying it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM