Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading