How to receive an event at each bar? #176
-
Hi, I'd like to receive an event at each bar while playing the midi file. Many thanks in advance..! |
Beta Was this translation helpful? Give feedback.
Answered by
melanchall
Apr 27, 2022
Replies: 1 comment 3 replies
-
Hi, Interesting task. Can't provide an easy way, you need some extra coding here. First, declare these constants and fields: private const int _checkFrequency = 10;
private static int _ticks = -1;
private static TimeSpan[] _barsStarts;
private static IEnumerator<TimeSpan> _barsStartsEnumerator;
private static bool _barsStartsEnumerated;
Well, next: var tickGenerator = new HighPrecisionTickGenerator();
tickGenerator.TickGenerated += OnTickGenerated; And next: var tempoMap = midiFile.GetTempoMap();
_barsStarts = Enumerable
.Range(0, (int)midiFile.GetDuration<BarBeatTicksTimeSpan>().Bars)
.Select(bar => (TimeSpan)TimeConverter.ConvertTo<MetricTimeSpan>(new BarBeatTicksTimeSpan(bar), tempoMap))
.ToArray();
_barsStartsEnumerator = ((IEnumerable<TimeSpan>)_barsStarts).GetEnumerator();
_barsStartsEnumerated = !_barsStartsEnumerator.MoveNext();
_playback = midiFile.GetPlayback(new PlaybackSettings
{
ClockSettings = new MidiClockSettings
{
CreateTickGeneratorCallback = () => tickGenerator
}
}); And finally private static void OnTickGenerated(object sender, EventArgs e)
{
_ticks++;
if (_ticks % _checkFrequency == 0 && !_barsStartsEnumerated)
{
var barStart = _barsStartsEnumerator.Current;
if ((TimeSpan)_playback.GetCurrentTime<MetricTimeSpan>() > barStart)
{
// WE'RE ON BAR START; DO ACTIONS HERE
// for example, print new bar index:
var bar = _playback.GetCurrentTime<BarBeatTicksTimeSpan>().Bars;
Console.WriteLine($"Bar {bar} reached!");
_barsStartsEnumerated = !_barsStartsEnumerator.MoveNext();
}
}
} |
Beta Was this translation helpful? Give feedback.
3 replies
Answer selected by
garcon33
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi,
Interesting task. Can't provide an easy way, you need some extra coding here. First, declare these constants and fields:
static
here because I've tested the things within console app withstatic Main
. If you have non-static class, use fields without the keyword.Well, next:
And next: