Fire and recurring timed event at exactly 100 ms
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