Fire and recurring timed event at exactly 100 ms

MarinusK 26 Reputation points
2021-03-05T14:14:06.203+00:00

Hi,

I am playing around with recurring timed events to play samples with a drum-sequencer. It a Xamarin Forms app. I am currently testing as an UWP app.

It seems that the Timer elapsed event is not consistent with the elapsed time for each repeat event.

My attempt:

using System.Threading.Tasks;
using System.Timers;
namespace SimpleDrumSequencer.Services
{
    public class SimpleDrumSequencerService : ISimpleDrumSequencerService
    {
        public Timer SequencerTimer = new Timer(126);

        public SimpleDrumSequencerService()
        {
            SequencerTimer.Elapsed += OnTimedEvent;
        }

        private void OnTimedEvent(object source, ElapsedEventArgs e)
        {
            Position %= 16;

            foreach (var sequencerLane in SequencerLanes)
            {
                if (sequencerLane.SequencerSteps[Position].IsActive)
                    Task.Run(() => // Adding a Task.Run to call play audio actually minimizes gives a real differency by 5ms. 
                    {
                        sequencerLane.AudioPlayer.Play();
                    });
            }

            PositionChanged.Invoke(this, new PositionChangedEventArgs { Position = Position }); // Via the viewmodel the view gets updated. 
            Position++;
        }

        public ISimpleDrumSequencerService Start()
        {
            SequencerTimer.Start();
            IsRunning = true; 
            return this;
        }

        public ISimpleDrumSequencerService Stop()
        {
            SequencerTimer.Stop();
            IsRunning = false;
            return this;
        }

        public ISimpleDrumSequencerService SetVolume(double volume)
        {
            foreach (var audioPlayer in SequencerLanes.Select(o => o.AudioPlayer).ToList())
            {
                audioPlayer.Volume = volume;
            }
        }
    }
}

The full code can be found here: https://github.com/marinusklaassen/simpledrumsequencer

My question: How can I trigger an recurring event at a fixed timed interval, by for example a nearly fixed real time interval of 100 ms? With the least amount of deviation of the interval duration between each event.

Many thanks in advance!

Grt, Marinus

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,295 questions
.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,398 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,279 questions
0 comments No comments
{count} votes