joshwcomeau / use-sound

A React Hook for playing sound effects

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

stop or pause not working

artivilla opened this issue · comments

import { useEffect, useState } from "react";
import { SpeakerWaveIcon, SpeakerXMarkIcon } from "@heroicons/react/24/outline";
import useSound from "use-sound";

export const AudioPlayer = ({ url }) => {
  const [isPlaying, setIsPlaying] = useState(false);
  const [play, { sound, stop }] = useSound(url);

  useEffect(() => {
    sound?.on("play", () => setIsPlaying(true));
    sound?.on("stop", () => setIsPlaying(false));
    sound?.on("end", () => setIsPlaying(false));
    sound?.on("pause", () => setIsPlaying(false));
  }, [sound]);

  return (
    <button className="flex gap-x-2" onClick={isPlaying ? stop : play}>
      {isPlaying ? (
        <SpeakerWaveIcon className="w-6 h-auto" />
      ) : (
        <SpeakerXMarkIcon className="w-6 h-auto" />
      )}
      {isPlaying ? "Pause" : "Play"}
    </button>
  );
};

I definitely see sound being exported in the types but doens't seem to work. Using the latest version: 4.0.1. any suggestions?

onClick={() => {
isPlaying ? stop() : play();
}}

Looks like something changed in version 4 and there are no proper documentation about it

https://github.com/joshwcomeau/use-sound/releases/tag/4.0.0

Here's how we solved this:

import React from "react";
import useSound from 'use-sound';
import Music from '../assets/audio/Music.mp3';

const MusicPlayer = () => {
  const [isPlaying, setIsPlaying] = React.useState(false);

  const [playBoop, {pause}] = useSound(Music, {
    onplay: () => setIsPlaying(true),
    onend: () => setIsPlaying(false),
  });

  const togglePlay = () => {
    if (isPlaying) {
      pause();
    } else {
      playBoop();
    }
    setIsPlaying(!isPlaying);
  }

  return (
    <>
      <h2>Is playing: {isPlaying.toString()}</h2>
      <br />
      <button onClick={togglePlay}>Play sound</button>
    </>
  );
};

export default MusicPlayer;