thangngoc89 / react-howler

A React.js wrapper for howler.js (audio player)
https://khoanguyen.me/react-howler/
MIT License
364 stars 83 forks source link

Fade in OnPlay #134

Closed pekado closed 2 years ago

pekado commented 2 years ago

Hi!

Any ideas of how to fade in onPlay? I'm trying to use for loop but is not working.

 <ReactHowler
      src='./../resources/Nature.mp3'
      playing={isSound}
      ref={envSound}
      loop
      onPlay={(e) => {
        envSound.current.volume(0.001);
        for (
          let index = 0;
          index < envSound.current.props.volume * 1000;
          index++
        ) {
          envSound.current.volume(index / 1000);
        }
      }}
    />
Stenerson commented 2 years ago

I haven't tried this and it's been a while since I've done anything with the internals here but have you tried using Howler's fade method? https://github.com/goldfire/howler.js#fadefrom-to-duration-id

Without seeing the rest of your component I'm not sure if the way you're setting the ref is working either. You could try doing it like we're doing in the examples ref={(ref) => (envSuond = ref)} or using a useRef hook to see if that would help.

Hopefully this is somewhat helpful! Please let us know how you progress.

pekado commented 2 years ago

The ref is useRef hook. How can I use a Howler method in the component? full code:

import React, {useEffect, useRef} from 'react';
import ReactHowler from 'react-howler';

function EnvSound({isSound, isInLetter}) {
  const envSound = useRef();

  useEffect(() => {
    envSound.current.props.onStop(() => {
      console.log(isInLetter);
    });
    if (isInLetter) {
      console.log(envSound.current);
    }
  }, [isInLetter]);
  return (
    <ReactHowler
      src='./../resources/Nature.mp3'
      playing={isSound}
      ref={envSound}
      loop
      onPlay={(e) => {
        envSound.current.volume(0.001);
        for (
          let index = 0;
          index < envSound.current.props.volume * 1000;
          index++
        ) {
          envSound.current.volume(index / 1000);
        }
      }}
    />
  );
}
export default EnvSound;
Stenerson commented 2 years ago

I don't have time today to open the project and try things out but have you tried envSound.current.howler.volume(0.001); & envSound.current.howler.volume(index / 1000);?

A new useEffect watching for changes in envSound could work as well:

useEffect(() => {
    if (envSound.current) {
      envSound.current.howler.fade(0.0, 1.0, 1000)
    };
  }, [envSound]);

One more thing to check out is this repo from a previous issue/PR that had a working "fade out" example: https://github.com/svlapin/react-howler/blob/feature/fade-example/examples/react/src/players/Fade.js

The code there is a bit dated (2018) but it shows a working example.

I hope that helps!!

pekado commented 2 years ago

UseEffect worked !