using System;
using System.IO;
using System.Text;
namespace NAudio.Midi
{
///
/// Represents a MIDI tempo event
///
public class TempoEvent : MetaEvent
{
private int microsecondsPerQuarterNote;
///
/// Reads a new tempo event from a MIDI stream
///
/// The MIDI stream
/// the data length
public TempoEvent(BinaryReader br,int length)
{
if(length != 3)
{
throw new FormatException("Invalid tempo length");
}
microsecondsPerQuarterNote = (br.ReadByte() << 16) + (br.ReadByte() << 8) + br.ReadByte();
}
///
/// Creates a new tempo event with specified settings
///
/// Microseconds per quarter note
/// Absolute time
public TempoEvent(int microsecondsPerQuarterNote, long absoluteTime)
: base(MetaEventType.SetTempo,3,absoluteTime)
{
this.microsecondsPerQuarterNote = microsecondsPerQuarterNote;
}
///
/// Creates a deep clone of this MIDI event.
///
public override MidiEvent Clone() => (TempoEvent)MemberwiseClone();
///
/// Describes this tempo event
///
/// String describing the tempo event
public override string ToString()
{
return String.Format("{0} {2}bpm ({1})",
base.ToString(),
microsecondsPerQuarterNote,
(60000000 / microsecondsPerQuarterNote));
}
///
/// Microseconds per quarter note
///
public int MicrosecondsPerQuarterNote
{
get { return microsecondsPerQuarterNote; }
set { microsecondsPerQuarterNote = value; }
}
///
/// Tempo
///
public double Tempo
{
get { return (60000000.0/microsecondsPerQuarterNote); }
set { microsecondsPerQuarterNote = (int) (60000000.0/value); }
}
///
/// Calls base class export first, then exports the data
/// specific to this event
/// MidiEvent.Export
///
public override void Export(ref long absoluteTime, BinaryWriter writer)
{
base.Export(ref absoluteTime, writer);
writer.Write((byte) ((microsecondsPerQuarterNote >> 16) & 0xFF));
writer.Write((byte) ((microsecondsPerQuarterNote >> 8) & 0xFF));
writer.Write((byte) (microsecondsPerQuarterNote & 0xFF));
}
}
}