stop or pause not working
artivilla opened this issue · comments
Arti Villa commented
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 commented
onClick={() => {
isPlaying ? stop() : play();
}}
blockson commented
Looks like something changed in version 4 and there are no proper documentation about it
blockson commented
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;