Toggle play/pause button in Next with mp3 audio

972 Views Asked by At

I'm building my website and i want a button at the bottom of my page, that will play/pause a song using useSound. It plays when i first click, but then i can't get my song to stop.

Can anyone point me in the right direction? Please see my code below.

import useSound from 'use-sound';
import galaxySfx from '../../public/sounds/galaxy.mp3';
import styles from "./sound.module.scss";
import Aos from "aos";
import "aos/dist/aos.css";

const PlayButton = ({}) => {

  const [play, { stop, isPlaying }] = useSound(galaxySfx);

  function playSong() {
    isPlaying === true;
    play(); 
  }

  function stopSong() {
    isPlaying === false;
    stop();
  }
  
  return (
    <div className={styles.playButton}>
       <button 
        data-aos="zoom-in"
        data-aos-offset="100"
        onClick={isPlaying ? stopSong() : playSong()}
        >
         
    </button>
    </div>
  );
};

export default PlayButton;

3

There are 3 best solutions below

1
a.mola On BEST ANSWER

After reading the use-sound documentation, I didn't see any isPlaying value from the second returned value you're destructuring.

So isPlaying will be undefined, but you can keep track of the playing state with a useState.

...

import { useState } from "react";

const PlayButton = ({}) => {
  const [isPlaying, setIsPlaying] = useState(false);
  const [play, { stop }] = useSound(galaxySfx);

  function playSong() {
    setIsPlaying(true);
    play();
  }

  function stopSong() {
    setIsPlaying(false);
    stop();
  }

The onClick prop expects a function to be called, so you shouldn't call the any of the functions you pass to it.

  return (
    <div className={styles.playButton}>
      <button
        data-aos="zoom-in"
        data-aos-offset="100"
        onClick={isPlaying ? stopSong : playSong}
      >
        
      </button>
    </div>
  );
}
2
Ceco Milchev On

You could use the same handler for both operations. Check the state of the isPlaying variable and act accordingly:

function togglePlay(){
    if(isPlaying){
        stop();
    } else{
        play();
    }
}
0
Chemi Adel On

Just remove bracket, in this way functions won't run unless you onClick

onClick={isPlaying ? stop: play}