Home > front end >  how to stop song on toggle button in react js
how to stop song on toggle button in react js

Time:11-02

This is the shortcode for play song on toggle button and my problem is when I click the toggle button to pause the music did not paused

import { React, useState } from 'react';    
import './audio.css';
import music from './BLOOD.mp3';

const PlaySong = () => {
var song = new Audio(music);
const [playMusic, setPlayMusic] = useState(false);
const handlePlayMusic = () => {
let state = !playMusic;
setPlayMusic(state);
console.log(state);
if(state === true){
song.play()
} else {
song.pause();  // the song did not stop when I call this method I don't 
know why        
}
}
return (
    <div className="container">
        <div className="button r" id="button-4">
            <input type="checkbox" className="checkbox" onChange= 
            {handlePlayMusic} />
            <div className="knobs" />
            <div className="layer" />
        </div>
    </div>
)
}

export default PlaySong

CodePudding user response:

In your code, playMusic state is always false meaning that your else block in handlePlayMusic() method will never be reached. You need to call setPlayMusic to toggle the state after playing/pausing.

Also, you don't need two variables for one single state, so you don't need state variable.

Suggested code:

const [playing, setPlaying] = useState(false);

const handlePlayClick = () => {
  setPlaying(prevPlaying => {
    if (prevPlaying) {
      song.pause();
    } else {
      song.play(); // might need to consider calling `resume`
    }

    return !prevPlaying;
  });
};

CodePudding user response:

You can do it with a toggle handler:

const [song, setSong] = useState({})
const [play, setPlay] = useState(false)

useEffect(() => {
  // create the song after component did mount
  const music = new Audio(music);
  setSong(music)
}, [])

const handlePlayMusic = () => {
  if(play) {
    song.pause();
  } else {
    song.paly();
  }

  setPlay(prevState => !prevState)
}

Explanation

with a click on handlePlayMusic for the first time, the play value is false, so the else block will invoke and the song will play. then the play state will be updated to true

Now, with the second click on the button, the if block will be executed and then the song will pause, similarly after that, the play state will be changed to false.

  • Related