Is there any plugin that support fade in and out in Flutter

446

I have created a method that allows you to fade in or fade out.

If you want to fade you must enter this:

3 seconds to increase the volume from 0.0 to 1.0.

Fade in:

fade (1.0, 0.0, 3 * 1000);

Fade out:

fade (0.0, 1.0, 3 * 1000);

If it works for you, don't forget to rate my answer, regards.

void fade( double to, double from, int len ) {
      double vol = from;
      double diff = to - from;
      double steps = (diff / 0.01).abs() ;
      int stepLen = Math.max(4, (steps > 0) ? len ~/ steps : len);
      int lastTick = DateTime.now().millisecondsSinceEpoch ;

      // // Update the volume value on each interval ticks
      Timer.periodic(new Duration(milliseconds: stepLen), ( Timer t ) {
          var now = DateTime.now().millisecondsSinceEpoch;
          var tick = (now - lastTick) / len;
          lastTick = now;
          vol += diff * tick;

          vol = Math.max(0, vol);
          vol = Math.min(1, vol);
          vol = (vol * 100).round() / 100;

          player.setVolume(vol); // change this

          if ( (to < from && vol <= to) || (to > from && vol >= to) ) {
            if (t != null) {
              t.cancel() ;
              t = null;
            }
            player.setVolume(vol); // change this
          } 
      });
  }
Share:
446
Islam Emam
Author by

Islam Emam

Updated on December 17, 2022

Comments

  • Islam Emam
    Islam Emam over 1 year

    I am working with the flutter_sound in Flutter. I simply want to fade in and fade out sound file in flutter