public static void WriteMidiFile(MidiSequence sequence, string filename) { MidiFileFormatWriter mffw = new MidiFileFormatWriter(filename); using (mffw) { // Write magic number mffw.WriteString(MidiFileFormat.midiFileMarker, false); // Write header size mffw.WriteUInt32(MidiFileFormat.midiFileHeaderLength); // Write header mffw.WriteUInt16(MidiFileFormat.midiFileVersion); mffw.WriteUInt16((ushort)sequence.Tracks.Count); mffw.WriteUInt16((ushort)((sequence.PPQN > 0) ? sequence.PPQN : (sequence.SMPTETempo | 0x8000))); // Write out the tracks for (int t = 0; t < sequence.Tracks.Count; t++) { WriteMidiTrack(mffw, sequence.Tracks[t]); } } }
static private void WriteMidiMetaMessage(MidiFileFormatWriter mffw, MidiMetaMessage message) { // Write out message type mffw.WriteUInt8((byte)message.Type); // Write out message content if (message is MidiMetaTrackSequenceNumberMessage) { var m = message as MidiMetaTrackSequenceNumberMessage; mffw.WriteVarLengthQuantity(2); mffw.WriteUInt16((ushort)m.SequenceNumber); } else if (message is MidiMetaTextMessage) { var m = message as MidiMetaTextMessage; mffw.WriteString(m.Text, true); } else if (message is MidiMetaMidiPortMessage) { var m = message as MidiMetaMidiPortMessage; mffw.WriteVarLengthQuantity(1); mffw.WriteUInt8((byte)m.Port); } else if (message is MidiMetaTempoMessage) { var m = message as MidiMetaTempoMessage; mffw.WriteVarLengthQuantity(3); mffw.WriteUInt24(m.Tempo); } else if (message is MidiMetaTimeSignatureMessage) { var m = message as MidiMetaTimeSignatureMessage; mffw.WriteVarLengthQuantity(4); mffw.WriteUInt8((byte)m.Numerator); mffw.WriteUInt8((byte)m.Denominator); mffw.WriteUInt8((byte)m.TicksInMetronomeClick); mffw.WriteUInt8((byte)m.No32ndNotesInQuarterNote); } else if (message is MidiMetaKeySignatureMessage) { var m = message as MidiMetaKeySignatureMessage; mffw.WriteVarLengthQuantity(2); mffw.WriteUInt8((byte)((m.Sharps > 0) ? m.Sharps : -m.Flats)); mffw.WriteUInt8((byte)(m.Minor ? 1 : 0)); } else if (message.Type == EMetaEventType.SequencerSpecific) { mffw.WriteVarLengthQuantity((uint)message.Body.Length); for (int b = 0; b < message.Body.Length; b++) { mffw.WriteUInt8(message.Body[b]); } } else if (message.Type == EMetaEventType.EndTrack) { mffw.WriteVarLengthQuantity(0); } else { throw new FormatException(string.Format("Found event type {0} - not supported!", message.GetType().FullName)); } }