adrianstevens / Xamarin-Plugins

Cross-platform Plugins for Xamarin, Xamarin.Forms and Windows
https://www.nuget.org/packages/Xam.Plugin.SimpleAudioPlayer/
MIT License
132 stars 53 forks source link

Extension Methods for ISimpleAudioPlayer (FadeIn/Out extension methods) #60

Open terinfire opened 4 years ago

terinfire commented 4 years ago

Sorry, I didn't fork -- but I came up with a way that should give you a little more feature-rich behavior, without having to go and implement it like crazy:

using Plugin.SimpleAudioPlayer;
using System.Threading;
using System.Threading.Tasks;

namespace Plugins.SimpleAudioPlayer.Extensions
{
    public static class ISimpleAudioPlayerExtensions
    {
        public static void FadeIn(this ISimpleAudioPlayer player, int milliseconds)
        {
            if (player == null || player.IsPlaying || milliseconds < 0) return;

            Task.Factory.StartNew(() =>
            {
                var step = milliseconds / 100;

                player.Volume = 0d;

                if (!player.IsPlaying)
                {
                    player.Play();
                }

                for (var i = 1; i <= 100; i++)
                {
                    player.Volume = (.01d * i);
                    Thread.Sleep(step);
                }
            });
        }

        public static void FadeOut(this ISimpleAudioPlayer player, int milliseconds)
        {
            if (player == null || !player.IsPlaying || milliseconds < 0) return;

            Task.Factory.StartNew(() =>
            {
                var step = milliseconds / 100;

                for (var i = 0; i < 100; i++)
                {
                    player.Volume = 1d - (.01d * i);
                    Thread.Sleep(step);
                }

                player.Stop();
                player.Volume = 1d;
            });
        }
    }
}

I've tested this in iOS and Android -- and it works REALLY well in both. Hopefully it will be useful to others (or you can incorporate it into the mainline -- my thought would be to just add an "ISimpleAudioPlayerExtensions.cs" file in the same directory as the ISimpleAudioPlayer definition.