Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

stop or pause not working #119

Open
artivilla opened this issue Sep 29, 2022 · 3 comments
Open

stop or pause not working #119

artivilla opened this issue Sep 29, 2022 · 3 comments

Comments

@artivilla
Copy link

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?

@guixiv
Copy link

guixiv commented Dec 21, 2022

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

@EthanBlockson
Copy link

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

@EthanBlockson
Copy link

EthanBlockson commented Dec 27, 2022

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;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants