How to know if audio ended in React js with toggle button

I have built a toggle button that turns on & off the audio, but my problem is how can I return the toggle button to off when the audio has finished and it’s building with react js if you can help me with some hints.

import { React, useState } from 'react';
import './playSong.css';
Import music from './THREE.mp3';

const PlaySong = () => {
const [activeSong, setActiveSong] = useState(false);
var [saveSong, setSaveSong] = useState({});

var drake = {
    value: 3,
    name: 'Energy',
    artist: 'Drake',
    audio: music, //
};

function handlePlayPause() {
    let states = !activeSong;
    setActiveSong(states);

    if (states) {  
        playSong(drake); // load song and play it
    }
    else {
        togglePause(saveSong); // pause song
    }

}

function playSong(drake) {
    var Song = new Audio(drake.audio);
    Song.play();
    setSaveSong(Song);
    return Song;
}

function togglePause(saveSong) {
    saveSong.pause();
    setSaveSong({});
}

return (
    <div className="container">
        <div className="button r" id="button-4">    
            <input type="checkbox" className="checkbox" onChange={handlePlayPause} checked= 
            {activeSong} />
            <div className="knobs" />
            <div className="layer" />
        </div>
    </div>
   )
  }

 export default PlaySong

>Solution :

Have you considered running all of your audio code through <audio> tag?

It has many events which you can supply handlers for.

https://www.w3schools.com/tags/ref_av_dom.asp

Specifically the ended or onended (maybe onEnded) event is the one you may want to look at.

https://www.w3schools.com/tags/av_event_ended.asp

Leave a Reply