E-Kuerschner / useAudioPlayer

React hooks for controlling audio on the web
MIT License
330 stars 36 forks source link

Access the fade method #65

Closed brianshano closed 2 years ago

brianshano commented 3 years ago

How can I access the fade method to fade in and out tracks? It's probably obvious but I can't find it...

I tried using the player function in useAudioPlayer but that doesn't seem to be the right approach

 const { togglePlayPause, ready, loading, playing, stop, play, player } = useAudioPlayer({
    src: file,
    format: "mp3",
    loop: true,
    autoplay: true,
    html5: isIos,
    // try here? nope
    onplay: () => {
      player.fade(0, 1, 5000);
    },
  });

  useEffect(() => {
    // trying here - nope
    isPlaying ? play() : player.fade(1, 0, 100)
  }, [isPlaying]);
E-Kuerschner commented 3 years ago

@brianshano thanks for the issue! Your approach looks very straight forward, I'm actually surprised it doesn't work. Tbh I have never used the fader method in my own apps, so I'm glad someone such as yourself has come along with that use case. Let me take a look next week and see if I can get a release out for you

E-Kuerschner commented 2 years ago

@brianshano sorry for such a long delay for returning to this. I think you should be able to access fade through the player object in your useEffect, however you will need to have the player as a dependency in the array as it initially starts as null.

useEffect(() => {
  if (player) {
    isPlaying ? play() : player.fade(1, 0, 100)
  }
  }, [player, isPlaying]);
E-Kuerschner commented 2 years ago

im also putting up a PR soon with ssome info on the docs to help with situations like this

E-Kuerschner commented 2 years ago

Added "fade" to the api of useAudioPlayer in https://www.npmjs.com/package/react-use-audio-player/v/1.2.5

brianshano commented 2 years ago

Thanks, I've managed to get it working.

For my use case, it doesn't work so well as I'm applying it to streaming internet radio - once I press play it starts with a quick flash of "1" volume then the fade kicks in and fades from 0 to 1. Not sure there is anything that can be done about that?

E-Kuerschner commented 2 years ago

There may be a difference with streaming audio however i got an example i was working with to start fading on play by doing something like this:

const { fade } = useAudioPlayer({
  src: mySound,
  autoplay: true
})

useEffect(() => {
  fade(0, 1, 4000)
}, [fade])
brianshano commented 2 years ago

Update: I remembered that the volume could be set on play initiation - so I set it to 0 and it worked.

Also I found the useEffect should also take "player" as a dependency and should only try fade when player=true otherwise it throws an error