/// <summary> /// Determines if this is an end track event /// </summary> public static bool IsEndTrack(MidiEvent midiEvent) { if (midiEvent != null) { MetaEvent me = midiEvent as MetaEvent; if (me != null) { return(me.MetaEventType == MetaEventType.EndTrack); } } return(false); }
/// <summary> /// Compares two MidiEvents /// Sorts by time, with EndTrack always sorted to the end /// </summary> public int Compare(MidiEvent x, MidiEvent y) { long xTime = x.AbsoluteTime; long yTime = y.AbsoluteTime; if (xTime == yTime) { // sort meta events before note events, except end track MetaEvent xMeta = x as MetaEvent; MetaEvent yMeta = y as MetaEvent; if (xMeta != null) { if (xMeta.MetaEventType == MetaEventType.EndTrack) { xTime = Int64.MaxValue; } else { xTime = Int64.MinValue; } } if (yMeta != null) { if (yMeta.MetaEventType == MetaEventType.EndTrack) { yTime = Int64.MaxValue; } else { yTime = Int64.MinValue; } } } return(xTime.CompareTo(yTime)); }
/// <summary> /// Opens a MIDI file for reading /// </summary> /// <param name="filename">Name of MIDI file</param> /// <param name="strictChecking">If true will error on non-paired note events</param> public MidiFile(Stream stream, bool strictChecking) { this.strictChecking = strictChecking; var br = new BinaryReader(stream); using (br) { byte[] bytes = br.ReadBytes(4); string chunkHeader = Encoding.UTF8.GetString(bytes, 0, bytes.Length); if (chunkHeader != "MThd") { throw new FormatException("Not a MIDI file - header chunk missing"); } uint chunkSize = SwapUInt32(br.ReadUInt32()); if (chunkSize != 6) { throw new FormatException("Unexpected header chunk length"); } // 0 = single track, 1 = multi-track synchronous, 2 = multi-track asynchronous fileFormat = SwapUInt16(br.ReadUInt16()); Debug.Log("MIDI FILE FORMAT : " + fileFormat.ToString()); int tracks = SwapUInt16(br.ReadUInt16()); deltaTicksPerQuarterNote = SwapUInt16(br.ReadUInt16()); events = new MidiEventCollection((fileFormat == 0) ? 0 : 1, deltaTicksPerQuarterNote); for (int n = 0; n < tracks; n++) { events.AddTrack(); } long absoluteTime = 0; for (int track = 0; track < tracks; track++) { if (fileFormat == 1) { absoluteTime = 0; } bytes = br.ReadBytes(4); chunkHeader = Encoding.UTF8.GetString(bytes, 0, bytes.Length); if (chunkHeader != "MTrk") { throw new FormatException("Invalid chunk header"); } chunkSize = SwapUInt32(br.ReadUInt32()); long startPos = br.BaseStream.Position; MidiEvent me = null; var outstandingNoteOns = new List <NoteOnEvent>(); while (br.BaseStream.Position < startPos + chunkSize) { me = MidiEvent.ReadNextEvent(br, me); absoluteTime += me.DeltaTime; me.AbsoluteTime = absoluteTime; events[track].Add(me); if (me.CommandCode == MidiCommandCode.NoteOn) { NoteEvent ne = (NoteEvent)me; if (ne.Velocity > 0) { outstandingNoteOns.Add((NoteOnEvent)ne); } else { // don't remove the note offs, even though // they are annoying // events[track].Remove(me); FindNoteOn(ne, outstandingNoteOns); } } else if (me.CommandCode == MidiCommandCode.NoteOff) { FindNoteOn((NoteEvent)me, outstandingNoteOns); } else if (me.CommandCode == MidiCommandCode.MetaEvent) { MetaEvent metaEvent = (MetaEvent)me; if (metaEvent.MetaEventType == MetaEventType.EndTrack) { //break; // some dodgy MIDI files have an event after end track if (strictChecking) { if (br.BaseStream.Position < startPos + chunkSize) { throw new FormatException(String.Format("End Track event was not the last MIDI event on track {0}", track)); } } } } } if (outstandingNoteOns.Count > 0) { if (strictChecking) { throw new FormatException(String.Format("Note ons without note offs {0} (file format {1})", outstandingNoteOns.Count, fileFormat)); } } if (br.BaseStream.Position != startPos + chunkSize) { throw new FormatException(String.Format("Read too far {0}+{1}!={2}", chunkSize, startPos, br.BaseStream.Position)); } } } }
/// <summary> /// Reads a meta-event from a stream /// </summary> /// <param name="br">A binary reader based on the stream of MIDI data</param> /// <returns>A new MetaEvent object</returns> public static MetaEvent ReadMetaEvent(BinaryReader br) { MetaEventType metaEvent = (MetaEventType)br.ReadByte(); int length = ReadVarInt(br); MetaEvent me = new MetaEvent(); switch (metaEvent) { case MetaEventType.TrackSequenceNumber: // Sets the track's sequence number. me = new TrackSequenceNumberEvent(br, length); break; case MetaEventType.TextEvent: // Text event case MetaEventType.Copyright: // Copyright case MetaEventType.SequenceTrackName: // Sequence / Track Name case MetaEventType.TrackInstrumentName: // Track instrument name case MetaEventType.Lyric: // lyric case MetaEventType.Marker: // marker case MetaEventType.CuePoint: // cue point case MetaEventType.ProgramName: case MetaEventType.DeviceName: me = new TextEvent(br, length); break; case MetaEventType.EndTrack: // This event must come at the end of each track if (length != 0) { throw new FormatException("End track length"); } break; case MetaEventType.SetTempo: // Set tempo me = new TempoEvent(br, length); break; case MetaEventType.TimeSignature: // Time signature me = new TimeSignatureEvent(br, length); break; case MetaEventType.KeySignature: // Key signature me = new KeySignatureEvent(br, length); break; case MetaEventType.SequencerSpecific: // Sequencer specific information me = new SequencerSpecificEvent(br, length); break; case MetaEventType.SmpteOffset: me = new SmpteOffsetEvent(br, length); break; default: //System.Windows.Forms.MessageBox.Show(String.Format("Unsupported MetaEvent {0} length {1} pos {2}",metaEvent,length,br.BaseStream.Position)); me.data = br.ReadBytes(length); if (me.data.Length != length) { throw new FormatException("Failed to read metaevent's data fully"); } break; } me.metaEvent = metaEvent; me.metaDataLength = length; return(me); }
/// <summary> /// Constructs a MidiEvent from a BinaryStream /// </summary> /// <param name="br">The binary stream of MIDI data</param> /// <param name="previous">The previous MIDI event (pass null for first event)</param> /// <returns>A new MidiEvent</returns> public static MidiEvent ReadNextEvent(BinaryReader br, MidiEvent previous) { int deltaTime = MidiEvent.ReadVarInt(br); MidiCommandCode commandCode; int channel = 1; byte b = br.ReadByte(); if ((b & 0x80) == 0) { // a running command - command & channel are same as previous commandCode = previous.CommandCode; channel = previous.Channel; br.BaseStream.Position--; // need to push this back } else { if ((b & 0xF0) == 0xF0) { // both bytes are used for command code in this case commandCode = (MidiCommandCode)b; } else { commandCode = (MidiCommandCode)(b & 0xF0); channel = (b & 0x0F) + 1; } } MidiEvent me; switch (commandCode) { case MidiCommandCode.NoteOn: me = new NoteOnEvent(br); break; case MidiCommandCode.NoteOff: case MidiCommandCode.KeyAfterTouch: me = new NoteEvent(br); break; case MidiCommandCode.ControlChange: me = new ControlChangeEvent(br); break; case MidiCommandCode.PatchChange: me = new PatchChangeEvent(br); break; case MidiCommandCode.ChannelAfterTouch: me = new ChannelAfterTouchEvent(br); break; case MidiCommandCode.PitchWheelChange: me = new PitchWheelChangeEvent(br); break; case MidiCommandCode.TimingClock: case MidiCommandCode.StartSequence: case MidiCommandCode.ContinueSequence: case MidiCommandCode.StopSequence: me = new MidiEvent(); break; case MidiCommandCode.Sysex: me = SysexEvent.ReadSysexEvent(br); break; case MidiCommandCode.MetaEvent: me = MetaEvent.ReadMetaEvent(br); break; default: throw new FormatException(String.Format("Unsupported MIDI Command Code {0:X2}", (byte)commandCode)); } me.channel = channel; me.deltaTime = deltaTime; me.commandCode = commandCode; return(me); }