Code: Select all
inline float TempoToSecondsPerBeat(float tempo)
{
assert(tempo > 0.0f);
return 60.0f / tempo;
}
inline float TempoToSamplesPerBeat(float tempo, float sampleRate)
{
assert(tempo > 0.0f);
assert(sampleRate >= 0.0f);
return TempoToSecondsPerBeat(tempo) * sampleRate;
}
We can build on this:
Code: Select all
enum NoteType
{
None,
WholeNote,
DottedHalfNote,
HalfNote,
HalfNoteTriplet,
DottedQuarterNote,
QuarterNote,
QuarterNoteTriplet,
DottedEigthNote,
EigthNote,
EigthNoteTriplet,
DottedSixteenthNote,
SixteenthNote,
SixteenthNoteTriplet,
DottedThirtySecondNote,
ThirtySecondNote,
ThirtySecondNoteTriplet,
NoteTypeCount
};
Code: Select all
// Assumes 4/4 time signature. Could be modified to take other
// time signatures into account.
inline float CalculateMidiSyncScaler(int barCount, int noteType)
{
static const float Scalers[NoteTypeCount] =
{
0.0f,
4.0f,
3.0f,
2.0f,
1.333333f,
1.5f,
1.0f,
0.666666f,
0.75f,
0.5f,
0.333333f,
0.375f,
0.25f,
0.1666666f,
0.1875f,
0.125f,
0.083333f
};
assert(barCount >= 0);
assert((noteType >= 0) && (noteType < NoteTypeCount));
return barCount * Scalers[WholeNote] + Scalers[noteType];
}
Usage:
Code: Select all
// Say we're setting the delay time for a delay effect. MIDI sync
// is set to quarter-note resolution:
// The tempo is given to us earlier with a call to getTimeInfo().
float seconds = TempoToSecondsPerBeat(tempo);
// Calculate MIDI sync scaler for quarter-note resolution.
float scaler = CalculateMidiSyncScaler(0, QuarterNote);
// Scale delay time to MIDI sync resolution.
float delayTime = seconds * scaler;
// Finally, set the delay time.
delay.SetDelayTime(delayTime);
