public MidiPlayer(Beeper beeper, string fileName) { midiFile = new MidiFile(fileName); this.beeper = beeper; frequency = new MidiFrequency(); }
static public List<UVoicePart> Load(string file, UProject project) { List<UVoicePart> resultParts = new List<UVoicePart>(); MidiFile midi = new MidiFile(file); for (int i = 0; i < midi.Tracks; i++) { Dictionary<int, UVoicePart> parts = new Dictionary<int, UVoicePart>(); foreach (var e in midi.Events.GetTrackEvents(i)) if (e is NoteOnEvent) { var _e = e as NoteOnEvent; if (!parts.ContainsKey(_e.Channel)) parts.Add(_e.Channel, new UVoicePart()); var note = project.CreateNote( _e.NoteNumber, (int)_e.AbsoluteTime * project.Resolution / midi.DeltaTicksPerQuarterNote, _e.NoteLength * project.Resolution / midi.DeltaTicksPerQuarterNote); parts[e.Channel].Notes.Add(note); } foreach (var pair in parts) { pair.Value.DurTick = pair.Value.GetMinDurTick(project); resultParts.Add(pair.Value); } } return resultParts; }
public void ReImportMIDI() { Debug.Log("MIDIReceiver: About to load " + MIDIResourcePath); MidiFile mid = new MidiFile(MIDIResourcePath, false); if (mid.Events == null) { Debug.Log("MIDIReceiver: Resource load failed- " + MIDIResourcePath); return; } _noteOns = new List<NoteInfo>(); foreach (MidiEvent ev in mid.Events[MIDITrackIdx]) { NoteOnEvent noteEvent = ev as NoteOnEvent; if (noteEvent != null) { try { NoteInfo newNote = new NoteInfo(); newNote.NoteNumber = noteEvent.NoteNumber; newNote.NoteOnBeat = MIDITimeMult*((float)noteEvent.AbsoluteTime / (float)mid.DeltaTicksPerQuarterNote); newNote.DurationBeats = MIDITimeMult*((float)noteEvent.NoteLength / (float)mid.DeltaTicksPerQuarterNote); newNote.Velocity = noteEvent.Velocity / 127.0f; _noteOns.Add(newNote); Debug.Log(" imported midi Note " + noteEvent.NoteNumber + " at beat " + newNote.NoteOnBeat + " duration " + newNote.DurationBeats); } catch (System.SystemException e) { Debug.Log("Error during midi import: " + e.Message); } } } }
static void Main(string[] args) { Console.Write("Enter midi file name: "); string file = Console.ReadLine(); MidiFile midiFile = new MidiFile(file); Console.WriteLine("Converting..."); TimeSpan startTime = TimeSpan.FromTicks(DateTime.Now.Ticks); MusicTwo music = MusicTwo.FromMidiFile(midiFile); Console.Write("Saving... "); music.SaveAsCFilesBest(file); Console.WriteLine("Done in {0}!", TimeSpan.FromTicks(DateTime.Now.Ticks) - startTime); ConsoleKeyInfo enteredKey; do { Console.Write("Play track?(Y/N) "); enteredKey = Console.ReadKey(); Console.WriteLine(); } while (enteredKey.KeyChar != 'Y' & enteredKey.KeyChar != 'N' & enteredKey.KeyChar != 'y' & enteredKey.KeyChar != 'n'); if (enteredKey.KeyChar == 'Y' || enteredKey.KeyChar == 'y') music.Play(); Console.Write("Press any key to continue..."); Console.ReadKey(); }
public MainWindow() { MidiFile midiFile = new MidiFile("KHB 299.mid"); for (int i = 0; i < midiFile.Events.Count(); i++) { foreach (MidiEvent midiEvent in midiFile.Events[i]) { int a = 10; } } InitializeComponent(); MessageBox.Show("Meh"); }
public string Describe(string fileName) { MidiFile mf = new MidiFile(fileName, false); StringBuilder sb = new StringBuilder(); sb.AppendFormat("Format {0}, Tracks {1}, Delta Ticks Per Quarter Note {2}\r\n", mf.FileFormat, mf.Tracks, mf.DeltaTicksPerQuarterNote); int beatsPerMeasure = FindBeatsPerMeasure(mf.Events[0]); for (int n = 0; n < mf.Tracks; n++) { foreach (MidiEvent midiEvent in mf.Events[n]) { if(!MidiEvent.IsNoteOff(midiEvent)) { sb.AppendFormat("{0} {1}\r\n", ToMBT(midiEvent.AbsoluteTime, mf.DeltaTicksPerQuarterNote, beatsPerMeasure), midiEvent); } } } return sb.ToString(); }
public string Describe(string fileName) { MidiFile mf = new MidiFile(fileName, false); StringBuilder sb = new StringBuilder(); sb.AppendFormat("Format {0}, Tracks {1}, Delta Ticks Per Quarter Note {2}\r\n", mf.FileFormat, mf.Tracks, mf.DeltaTicksPerQuarterNote); var timeSignature = mf.Events[0].OfType<TimeSignatureEvent>().FirstOrDefault(); for (int n = 0; n < mf.Tracks; n++) { foreach (MidiEvent midiEvent in mf.Events[n]) { if(!MidiEvent.IsNoteOff(midiEvent)) { sb.AppendFormat("{0} {1}\r\n", ToMBT(midiEvent.AbsoluteTime, mf.DeltaTicksPerQuarterNote, timeSignature), midiEvent); } } } return sb.ToString(); }
public IEnumerable <Note> ReadToEnd() { if (!File.Exists(this.MidiFile)) { throw new FileNotFoundException("Midi file not found", this.MidiFile); } var midi = new NAudio.Midi.MidiFile(this.MidiFile); var timeSignature = midi.Events[0].OfType <TimeSignatureEvent>().FirstOrDefault(); int ticksPerQuarterNote = midi.DeltaTicksPerQuarterNote; //int ticksPerBar = ticksPerQuarterNote * 4; int quarterNote = 96; int track = (this.Track.HasValue) ? this.Track.Value : 0; if (track >= midi.Tracks) { track = midi.Tracks - 1; } foreach (MidiEvent @event in midi.Events[track]) { if (MidiCommandCode.NoteOn == @event.CommandCode) { NoteOnEvent noteOn = @event as NoteOnEvent; if (noteOn != null) { int ticks = noteOn.NoteLength; yield return(new Note(noteOn.NoteNumber) { Duration = ticks / quarterNote }); } } } }
/// <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> // Token: 0x0600050B RID: 1291 RVA: 0x00010D64 File Offset: 0x0000EF64 public MidiFile(string filename, bool strictChecking) { this.strictChecking = strictChecking; BinaryReader binaryReader = new BinaryReader(File.OpenRead(filename)); using (binaryReader) { string @string = Encoding.UTF8.GetString(binaryReader.ReadBytes(4)); if (@string != "MThd") { throw new FormatException("Not a MIDI file - header chunk missing"); } uint num = MidiFile.SwapUInt32(binaryReader.ReadUInt32()); if (num != 6u) { throw new FormatException("Unexpected header chunk length"); } this.fileFormat = MidiFile.SwapUInt16(binaryReader.ReadUInt16()); int num2 = (int)MidiFile.SwapUInt16(binaryReader.ReadUInt16()); this.deltaTicksPerQuarterNote = MidiFile.SwapUInt16(binaryReader.ReadUInt16()); this.events = new MidiEventCollection((this.fileFormat == 0) ? 0 : 1, (int)this.deltaTicksPerQuarterNote); for (int i = 0; i < num2; i++) { this.events.AddTrack(); } long num3 = 0L; for (int j = 0; j < num2; j++) { if (this.fileFormat == 1) { num3 = 0L; } @string = Encoding.UTF8.GetString(binaryReader.ReadBytes(4)); if (@string != "MTrk") { throw new FormatException("Invalid chunk header"); } num = MidiFile.SwapUInt32(binaryReader.ReadUInt32()); long position = binaryReader.BaseStream.Position; MidiEvent midiEvent = null; List <NoteOnEvent> list = new List <NoteOnEvent>(); while (binaryReader.BaseStream.Position < position + (long)((ulong)num)) { midiEvent = MidiEvent.ReadNextEvent(binaryReader, midiEvent); num3 += (long)midiEvent.DeltaTime; midiEvent.AbsoluteTime = num3; this.events[j].Add(midiEvent); if (midiEvent.CommandCode == MidiCommandCode.NoteOn) { NoteEvent noteEvent = (NoteEvent)midiEvent; if (noteEvent.Velocity > 0) { list.Add((NoteOnEvent)noteEvent); } else { this.FindNoteOn(noteEvent, list); } } else if (midiEvent.CommandCode == MidiCommandCode.NoteOff) { this.FindNoteOn((NoteEvent)midiEvent, list); } else if (midiEvent.CommandCode == MidiCommandCode.MetaEvent) { MetaEvent metaEvent = (MetaEvent)midiEvent; if (metaEvent.MetaEventType == MetaEventType.EndTrack && strictChecking && binaryReader.BaseStream.Position < position + (long)((ulong)num)) { throw new FormatException(string.Format("End Track event was not the last MIDI event on track {0}", j)); } } } if (list.Count > 0 && strictChecking) { throw new FormatException(string.Format("Note ons without note offs {0} (file format {1})", list.Count, this.fileFormat)); } if (binaryReader.BaseStream.Position != position + (long)((ulong)num)) { throw new FormatException(string.Format("Read too far {0}+{1}!={2}", num, position, binaryReader.BaseStream.Position)); } } } }
public void OpenMidiFile() { return; //NAudio.Midi.MidiFile midiFile = new MidiFile(@"D:\Libraries\Musics\Midi\beethoven-pour-elise.mid"); //flourish //town NAudio.Midi.MidiFile midiFile = new MidiFile(@"D:\GDD\Log\Geff\TheGrid\TheGrid\TheGrid\Files\Sound\Midi\town.mid"); string part = String.Empty; TimeSignatureEvent lastTimeSignature = null;// new TimeSignatureEvent(4,4,24,32, List<NoteEvent> listNote = new List<NoteEvent>(); Dictionary<float, string> dicNoteType = new Dictionary<float, string>(); //dicNoteType.Add(1.75f * 4f, "Ronde double pointée"); //dicNoteType.Add(1.5f * 4f, "Ronde pointée"); dicNoteType.Add(4f, "Ronde"); dicNoteType.Add(1.75f * 2f, "Blanche double pointée"); dicNoteType.Add(1.5f * 2f, "Blanche pointée"); dicNoteType.Add(2f, "Blanche"); dicNoteType.Add(1.75f * 1f, "Noire double pointée"); dicNoteType.Add(1.5f * 1f, "Noire pointée"); dicNoteType.Add(1f, "Noire"); dicNoteType.Add(1.75f * 0.5f, "Croche double pointée"); dicNoteType.Add(1.5f * 0.5f, "Croche pointée"); dicNoteType.Add(0.5f, "Croche"); dicNoteType.Add(1.75f * 0.25f, "Double croche double pointée"); dicNoteType.Add(1.5f * 0.25f, "Double croche pointée"); dicNoteType.Add(0.25f, "Double croche"); dicNoteType.Add(1.75f * 0.125f, "Triple croche double pointée"); dicNoteType.Add(1.5f * 0.125f, "Triple croche pointée"); dicNoteType.Add(0.125f, "Triple croche"); dicNoteType.Add(1.75f * 0.0625f, "Quadruple croche double pointée"); dicNoteType.Add(1.5f * 0.0625f, "Quadruple croche pointée"); dicNoteType.Add(0.0625f, "Quadruple croche"); if (midiFile != null) { part += String.Format(" [ DeltaTicksPerQuarterNote : {0} ] ", midiFile.DeltaTicksPerQuarterNote); for (int i = 0; i < midiFile.Tracks; i++) { part += "\r\n"; foreach (MidiEvent midiEvent in midiFile.Events[i]) { NoteOnEvent noteEvent = midiEvent as NoteOnEvent; part += "\r\n"; if (midiEvent is TimeSignatureEvent) { lastTimeSignature = midiEvent as TimeSignatureEvent; part += String.Format(" [ {0} ] ", midiEvent.ToString()); } else if (noteEvent != null && noteEvent.CommandCode == MidiCommandCode.NoteOn) { int noteLength = 1; try { noteLength = noteEvent.NoteLength; } catch { } part += String.Format(" [ AbsoluteTime {0} # DeltaTime {1} # NoteName {2} # NoteNumber {3} # NoteLength {4} ] ", noteEvent.AbsoluteTime, noteEvent.DeltaTime, noteEvent.NoteName, noteEvent.NoteNumber, noteLength); float typeNote = (float)noteLength / (float)midiFile.DeltaTicksPerQuarterNote; string typeNoteString = String.Empty; if (dicNoteType.ContainsKey(typeNote)) typeNoteString = dicNoteType[typeNote]; part += String.Format(" OFF :: {0} :: {1}", typeNote, typeNoteString); listNote.Add(noteEvent); } else { part += String.Format(" [ {0} ] ", midiEvent.ToString()); } } } } int a = 0; }
public static Composition LoadFromMIDI(string filename) { Composition comp = new Composition(); comp.Tracks.Clear(); NAudio.Midi.MidiFile f = new MidiFile(filename); // if (f.Events.MidiFileType == 1) // return LoadMidiType1(f); f.Events.MidiFileType = 0; byte max_channels = 0; foreach(var trackEvent in f.Events) foreach (var e in trackEvent) if (e.Channel > max_channels) max_channels = (byte)e.Channel; max_channels++; Track[] tracks = new Track[max_channels]; MelodySequence[] seqs = new MelodySequence[max_channels]; TempoEvent[] tempos = new TempoEvent[max_channels]; for (byte i = 0; i < max_channels; i++ ) { tracks[i] = new Track(PatchNames.Acoustic_Grand, i); seqs[i] = new MelodySequence(); tempos[i] = new TempoEvent((int)(Note.ToRealDuration((int)Durations.qn, 60) * 1000), 0); tempos[i].Tempo = 60; } foreach(var trackEvents in f.Events) foreach (var e in trackEvents) { if (e as TempoEvent != null) { tempos[e.Channel] = (TempoEvent)e; } if (e as PatchChangeEvent != null) { var p = e as PatchChangeEvent; tracks[p.Channel].Instrument = (PatchNames)p.Patch; } NoteOnEvent on = e as NoteOnEvent; if (on != null && on.OffEvent != null) { int total_dur = Note.ToNoteLength((int)on.AbsoluteTime, f.DeltaTicksPerQuarterNote, tempos[on.Channel].Tempo); if (total_dur > seqs[on.Channel].Duration) seqs[on.Channel].AddPause(total_dur - seqs[on.Channel].Duration); int duration = Note.ToNoteLength(on.NoteLength, f.DeltaTicksPerQuarterNote, tempos[on.Channel].Tempo); seqs[on.Channel].AddNote(new Note(on.NoteNumber, (int)duration)); } } for(byte i = 0; i < max_channels; i++) { if(seqs[i].Length > 0) { tracks[i].AddSequence(seqs[i]); comp.Tracks.Add(tracks[i]); } } comp.NameTag = System.IO.Path.GetFileNameWithoutExtension(filename); return comp; }
/// <summary> /// Loads a Harmony Sequence though /// </summary> /// <param name="f"></param> /// <returns></returns> public static Composition LoadMidiType1(MidiFile f) { Composition comp = new Composition(); int c = 1; foreach(var trackEvents in f.Events) { Track t = new Track(); t.Channel = (byte)c++; TempoEvent tempo = new TempoEvent((int)(Note.ToRealDuration((int)Durations.qn, 60) * 1000000), 0); HarmonySequence seq = new HarmonySequence(); long lastAbsTime = -1; List<int> chordNotes = new List<int>(); int chordDuration = 0; PatchNames instr = (PatchNames)9999; bool add = true; foreach(var e in trackEvents) { if (e as TempoEvent != null) { tempo = (TempoEvent)e; } if (e as PatchChangeEvent != null) { var p = e as PatchChangeEvent; t.Instrument = (PatchNames)p.Patch; if(t.Instrument == instr) { break; } instr = t.Instrument; /*if(t.Duration < 1) { foreach(var t_ in comp.Tracks) if(t_.Instrument == (PatchNames)p.Patch) { t = t_; seq = t_.GetMainSequence() as HarmonySequence; add = false; break; } }*/ } NoteOnEvent on = e as NoteOnEvent; if (on != null && on.OffEvent != null) { int newDuration = Note.ToNoteLength(on.NoteLength, f.DeltaTicksPerQuarterNote, tempo.Tempo); if (on.AbsoluteTime == lastAbsTime && chordDuration==newDuration)//skip chords { chordNotes.Add(on.NoteNumber); } else { Chord lastChord = new Chord(chordNotes.ToArray(), chordDuration); chordNotes.Clear(); chordDuration = 0; seq.AddChord(lastChord); chordNotes.Add(on.NoteNumber); } chordDuration = newDuration; lastAbsTime = on.AbsoluteTime; } } if(chordNotes.Count > 0) { Chord lastChord = new Chord(chordNotes.ToArray(), chordDuration); chordNotes.Clear(); chordDuration = 0; seq.AddChord(lastChord); } t.AddSequence(seq); if (!comp.Tracks.Contains(t) && t.Duration > 0 && add) comp.Add(t); } return comp; }
public bool ConvertFile(string sourceFile, int fileType, int TrackNum, ICollection<MidiNotes> NoteCollection) { try { //MidiFile midiFile = new MidiFile(sourceFile); MidiFile midiFile = new MidiFile(sourceFile); if (fileType == -1) { fileType = midiFile.FileFormat; } EventRuleArgs eventRuleArgs = new EventRuleArgs(Path.GetFileNameWithoutExtension(sourceFile)); MidiEventCollection outputFileEvents = new MidiEventCollection(fileType, midiFile.DeltaTicksPerQuarterNote); bool hasNotes = false; int track = TrackNum; ; IList<MidiEvent> trackEvents = midiFile.Events[track]; // Notes the use of the Track reference, if invalid track is referenced then causes big issues IList<MidiEvent> outputEvents; if (fileType == 1 || track == 0) { outputEvents = new List<MidiEvent>(); } else { outputEvents = outputFileEvents[0]; } foreach (MidiEvent midiEvent in InsertEvents) { outputEvents.Add(midiEvent); } foreach (MidiEvent midiEvent in trackEvents) { outputEvents.Add(midiEvent); NoteOnEvent noteOnEvent = midiEvent as NoteOnEvent; if (noteOnEvent != null) { // Add to the midi collection if (!MidiEvent.IsNoteOff(noteOnEvent)) { MidiNotes tempnote = new MidiNotes(noteOnEvent); NoteCollection.Add(tempnote); }; //System.Diagnostics.Debug.Assert(noteOnEvent.OffEvent != null); hasNotes = true; outputEvents.Add(noteOnEvent.OffEvent); } //} } // Get the tempo events foreach (MidiEvent midiEvent in trackEvents) { //get the tempo and drop out of that track if (midiEvent is TempoEvent) { //tempo in milliseconds tempo = (midiEvent as TempoEvent).MicrosecondsPerQuarterNote / 1000; break; } //get the tempo and drop out of that track if (midiEvent is TimeSignatureEvent) { //Time sig timesig1 = (midiEvent as TimeSignatureEvent).Numerator; timesig2 = (midiEvent as TimeSignatureEvent).Denominator; break; } } if (fileType == 1 || track == 0) { outputFileEvents.AddTrack(outputEvents); } //} if (hasNotes) { //MidiFile.Export(destFile, outputFileEvents); } return hasNotes; } catch { MessageBox.Show("Invalid File or track number"); return false; } }
public static IEnumerable<Track> ParseMidi(string fileName) { var tracks = new List<Track>(); var file = new MidiFile(fileName); var tempo = 120; for(var trackNumber = 0; trackNumber < file.Tracks; ++trackNumber) { var events = file.Events[trackNumber]; var tempoEvent = events.FirstOrDefault(c => c is TempoEvent) as TempoEvent; if(tempoEvent != null) { tempo = (int)tempoEvent.Tempo; } } var channel = 0; for(var trackNumber = 0; trackNumber < file.Tracks; ++trackNumber, ++channel) { var phrases = new List<Phrase>(); var events = file.Events[trackNumber]; var path = events.FirstOrDefault(c => c is PatchChangeEvent) as PatchChangeEvent; if(path != null && PatchChangeEvent.GetPatchName(path.Patch) == "Steel Drums") { continue; } var mediaPatch = PatchChangeEvent.GetPatchName(path?.Patch ?? 0) .IndexOf("bass", StringComparison.InvariantCultureIgnoreCase) != -1 ? MediaPatch.Bass : MediaPatch.CleanGuitar; var notes = events.OfType<NoteOnEvent>().GroupBy(c => c.AbsoluteTime); long lastTime = 0; foreach(var noteCollection in notes) { if(noteCollection.Key - lastTime > 0) { var pauseTime = noteCollection.Key - lastTime; phrases.Add(new Phrase(pauseTime / WholeNoteDuration)); } var duration = noteCollection.Max(c => c.NoteLength); var phrase = new Phrase { Duration = duration / WholeNoteDuration, Notes = noteCollection.Select(c => Note.FromId(c.NoteNumber)).ToArray() }; lastTime = noteCollection.Key + duration; phrases.Add(phrase); } tracks.Add(new Track { Tempo = tempo, Patch = mediaPatch, Phrases = phrases.ToArray(), Channel = channel }); } return tracks; }
/// <summary> /// Creates MusicTwo instance using midi file /// </summary> /// <param name="midiFile">Midi file to use</param> /// <returns>Created MusicTwo instance</returns> public static MusicTwo FromMidiFile(MidiFile midiFile) { return FromMidiFile(midiFile, false); }
private void ProcessFile(string file, string outputFolder, string[] context) { bool copy = false; string fileName = Path.GetFileName(file); string target = Path.Combine(outputFolder, fileName); if (Path.GetExtension(file).ToLower() == ".mid") { MidiFile midiFile = new MidiFile(file); ConvertMidi(midiFile, target, CreateNewContext(context, Path.GetFileNameWithoutExtension(file))); filesConverted++; } else { copy = true; } if (copy) { if (settings.VerboseOutput) { LogTrace("Copying File {0} to {1}", fileName, target); } File.Copy(file, target); filesCopied++; } }
/// <summary> /// Creates MusicTwo instance using midi file /// </summary> /// <param name="midiFile">Midi file to use</param> /// <param name="firstNoteMode">Use first note mode. If some notes appears at same time, use the first one, else the last</param> /// <returns>Created MusicTwo instance</returns> public static MusicTwo FromMidiFile(MidiFile midiFile, bool firstNoteMode) { double tempo = 0; List<Track> tracks = new List<Track>(); for (int track_ = 1; track_ <= midiFile.Tracks; track_++) { Track track__ = new Track(); foreach (var e in midiFile.Events) { foreach (var ee in e) { if (ee is NoteEvent) { NoteEvent eee = (NoteEvent)ee; if (eee is NoteOnEvent) { var eeee = (NoteOnEvent)eee; Note nt = new Note(); nt.time = (int)(eeee.AbsoluteTime / (double)midiFile.DeltaTicksPerQuarterNote * tempo); nt.length = 0; if (eeee.OffEvent != null) nt.length = (int)(eeee.NoteLength / (double)midiFile.DeltaTicksPerQuarterNote * tempo); nt.number = eeee.NoteNumber; nt.instrument = track__.instrument; if (eeee.Channel == track_) track__.notes.Add(nt); } } if (ee is MetaEvent) { MetaEvent eee = (MetaEvent)ee; if (eee.MetaEventType == MetaEventType.SetTempo) { TempoEvent eeee = (TempoEvent)eee; tempo = eeee.MicrosecondsPerQuarterNote / 1000; } } if (ee is PatchChangeEvent) { PatchChangeEvent eee = (PatchChangeEvent)ee; if (eee.Channel == track_) track__.instrument = eee.Patch; } } } tracks.Add(track__); } for (int i = 0; i < tracks.Count; i++) { for (int ii = 0; ii < tracks[i].notes.Count; ii++) { if (tracks[i].notes[ii].length == 0) tracks[i].notes.RemoveAt(ii); } if (tracks[i].notes.Count == 0) { tracks.RemoveAt(i); i--; } } MusicTwo music = new MusicTwo(); for (int tracko = 0; tracko < tracks.Count; tracko++) { Track track = tracks[tracko]; TrackTwo nts = new TrackTwo(); NoteTwo ntt = new NoteTwo(); ntt.Number = 0; ntt.Length = 0; nts.Notes.Add(ntt); Note lastNote = (new Note()); Note en = new Note(); lastNote.time = 0; lastNote.number = 0; lastNote.length = 0; en.time = 0; en.number = 0; en.length = 0; for (int i = 0; i < track.notes.Last().time + track.notes.Last().length; i++) { Note nowNote = en; for (int ii = 0; ii < track.notes.Count; ii++) { if (i >= track.notes[ii].time && i <= track.notes[ii].time + track.notes[ii].length) { nowNote = track.notes[ii]; if (firstNoteMode) goto c1; } } c1: if (nts.Notes.Last().Number == nowNote.number) { nts.Notes.Last().Length++; continue; } else { NoteTwo nttt = new NoteTwo(); nttt.Number = nowNote.number; nttt.Length = 1; nttt.IsBass = isInstrumentBass(nowNote.instrument); nts.Notes.Add(nttt); } } music.tracks.Add(nts); } return music; }
public void OpenMidiFile(string fileName) { if (!File.Exists(fileName)) { Form1_Resize(null, null); return; } //NAudio.Midi.MidiFile midiFile = new MidiFile(@"D:\Libraries\Musics\Midi\beethoven-pour-elise.mid"); //flourish //town MidiFile midiFile = new MidiFile(fileName); string part = String.Empty; TimeSignatureEvent lastTimeSignature = null;// new TimeSignatureEvent(4,4,24,32, List<NoteEvent> listNote = new List<NoteEvent>(); Dictionary<float, string> dicNoteType = new Dictionary<float, string>(); //dicNoteType.Add(1.75f * 4f, "Ronde double pointée"); //dicNoteType.Add(1.5f * 4f, "Ronde pointée"); dicNoteType.Add(4f, "Ronde"); dicNoteType.Add(1.75f * 2f, "Blanche double pointée"); dicNoteType.Add(1.5f * 2f, "Blanche pointée"); dicNoteType.Add(2f, "Blanche"); dicNoteType.Add(1.75f * 1f, "Noire double pointée"); dicNoteType.Add(1.5f * 1f, "Noire pointée"); dicNoteType.Add(1f, "Noire"); dicNoteType.Add(1.75f * 0.5f, "Croche double pointée"); dicNoteType.Add(1.5f * 0.5f, "Croche pointée"); dicNoteType.Add(0.5f, "Croche"); dicNoteType.Add(1.75f * 0.25f, "Double croche double pointée"); dicNoteType.Add(1.5f * 0.25f, "Double croche pointée"); dicNoteType.Add(0.25f, "Double croche"); dicNoteType.Add(1.75f * 0.125f, "Triple croche double pointée"); dicNoteType.Add(1.5f * 0.125f, "Triple croche pointée"); dicNoteType.Add(0.125f, "Triple croche"); dicNoteType.Add(1.75f * 0.0625f, "Quadruple croche double pointée"); dicNoteType.Add(1.5f * 0.0625f, "Quadruple croche pointée"); dicNoteType.Add(0.0625f, "Quadruple croche"); music = new Music(); music.ListChanel = new List<Channel>(); Measure curMeasure = null; bool hasNote = false; StringBuilder partition = new StringBuilder(); if (midiFile != null) { part += String.Format(" [ DeltaTicksPerQuarterNote : {0} ] ", midiFile.DeltaTicksPerQuarterNote); for (int i = 0; i < midiFile.Tracks; i++) { Channel currentChannel = null; currentChannel = new Channel(); hasNote = false; partition.AppendLine(); foreach (MidiEvent midiEvent in midiFile.Events[i]) { NoteOnEvent noteEvent = midiEvent as NoteOnEvent; partition.AppendLine(); if (midiEvent is TimeSignatureEvent) { lastTimeSignature = midiEvent as TimeSignatureEvent; //part += String.Format(" [ {0} ] ", midiEvent.ToString()); partition.AppendLine(String.Format(" [ {0} ] ", midiEvent.ToString())); } else if (noteEvent != null && noteEvent.CommandCode == MidiCommandCode.NoteOn && noteEvent.Velocity > 0) { int noteLength = 1; noteLength = noteEvent.NoteLength; partition.AppendLine(String.Format(" [ AbsoluteTime {0} # DeltaTime {1} # NoteName {2} # NoteNumber {3} # NoteLength {4} # Channel {5}] ", noteEvent.AbsoluteTime, noteEvent.DeltaTime, noteEvent.NoteName, noteEvent.NoteNumber, noteLength, noteEvent.Channel)); float typeNote = (float)noteLength / (float)midiFile.DeltaTicksPerQuarterNote; string typeNoteString = String.Empty; if (dicNoteType.ContainsKey(typeNote)) typeNoteString = dicNoteType[typeNote]; partition.AppendLine(String.Format(" OFF :: {0} :: {1}", typeNote, typeNoteString)); listNote.Add(noteEvent); float measureLenght = (float)lastTimeSignature.Numerator * 4f / (float)lastTimeSignature.No32ndNotesInQuarterNote * (float)midiFile.DeltaTicksPerQuarterNote; Note newNote = new Note(); newNote.NoteLength = noteEvent.NoteLength; newNote.NoteName = noteEvent.NoteName; newNote.NoteNumber = noteEvent.NoteNumber; newNote.AbsoluteTime = noteEvent.AbsoluteTime; curMeasure = currentChannel.FindMeasure(noteEvent.AbsoluteTime); if (curMeasure == null) { int nbPrevMeasure = (int)(noteEvent.AbsoluteTime / measureLenght); curMeasure = new Measure(nbPrevMeasure * measureLenght, measureLenght); currentChannel.AddMeasure(curMeasure); } curMeasure.AddNote(newNote); hasNote = true; } else { partition.AppendLine(String.Format(" [ {0} ] ", midiEvent.ToString())); } } if (hasNote) { music.AddChannel(currentChannel); } } } Form1_Resize(null, null); }
private void ConvertMidi(MidiFile midiFile, string target, string[] context) { string fileNameWithoutExtension = context[context.Length - 1]; string name = null; long endTrackTime = -1; if (settings.UseFileName) { name = fileNameWithoutExtension; } if (settings.ApplyNamingRules) { if (ezdFileName.Match(fileNameWithoutExtension).Success) { name = CreateEzdName(context); } } int outputFileType = midiFile.FileFormat; int outputTrackCount; if (settings.OutputMidiType == OutputMidiType.Type0) { outputFileType = 0; } else if (settings.OutputMidiType == OutputMidiType.Type1) { outputFileType = 1; } if (outputFileType == 0) { outputTrackCount = 1; } else { if (midiFile.FileFormat == 0) outputTrackCount = 2; else outputTrackCount = midiFile.Tracks; } MidiEventCollection events = new MidiEventCollection(outputFileType, midiFile.DeltaTicksPerQuarterNote); for (int track = 0; track < outputTrackCount; track++) { events.AddTrack(); } if (name != null) { for (int track = 0; track < outputTrackCount; track++) { events[track].Add(new TextEvent(name, MetaEventType.SequenceTrackName, 0)); } if (settings.AddNameMarker) { events[0].Add(new TextEvent(name, MetaEventType.Marker, 0)); } } foreach (MidiEvent midiEvent in midiFile.Events[0]) { if (settings.OutputChannelNumber != -1) midiEvent.Channel = settings.OutputChannelNumber; MetaEvent metaEvent = midiEvent as MetaEvent; if (metaEvent != null) { bool exclude = false; switch (metaEvent.MetaEventType) { case MetaEventType.SequenceTrackName: if (name != null) { exclude = true; } break; case MetaEventType.SequencerSpecific: exclude = settings.RemoveSequencerSpecific; break; case MetaEventType.EndTrack: exclude = settings.RecreateEndTrackMarkers; endTrackTime = metaEvent.AbsoluteTime; break; case MetaEventType.SetTempo: if (metaEvent.AbsoluteTime != 0 && settings.RemoveExtraTempoEvents) { LogWarning("Removing a tempo event ({0}bpm) at {1} from {2}", ((TempoEvent)metaEvent).Tempo, metaEvent.AbsoluteTime, target); exclude = true; } break; case MetaEventType.TextEvent: if (settings.TrimTextEvents) { TextEvent textEvent = (TextEvent)midiEvent; textEvent.Text = textEvent.Text.Trim(); if (textEvent.Text.Length == 0) { exclude = true; } } break; case MetaEventType.Marker: if (settings.AddNameMarker && midiEvent.AbsoluteTime == 0) { exclude = true; } if (settings.RemoveExtraMarkers && midiEvent.AbsoluteTime > 0) { LogWarning("Removing a marker ({0}) at {1} from {2}", ((TextEvent)metaEvent).Text, metaEvent.AbsoluteTime, target); exclude = true; } break; } if (!exclude) { events[0].Add(midiEvent); } } else { if (outputFileType == 1) events[1].Add(midiEvent); else events[0].Add(midiEvent); } } // now do track 1 (Groove Monkee) for (int inputTrack = 1; inputTrack < midiFile.Tracks; inputTrack++) { int outputTrack; if(outputFileType == 1) outputTrack = inputTrack; else outputTrack = 0; foreach (MidiEvent midiEvent in midiFile.Events[inputTrack]) { if (settings.OutputChannelNumber != -1) midiEvent.Channel = settings.OutputChannelNumber; bool exclude = false; MetaEvent metaEvent = midiEvent as MetaEvent; if (metaEvent != null) { switch (metaEvent.MetaEventType) { case MetaEventType.SequenceTrackName: if (name != null) { exclude = true; } break; case MetaEventType.SequencerSpecific: exclude = settings.RemoveSequencerSpecific; break; case MetaEventType.EndTrack: exclude = settings.RecreateEndTrackMarkers; break; } } if (!exclude) { events[outputTrack].Add(midiEvent); } } if(outputFileType == 1 && settings.RecreateEndTrackMarkers) { AppendEndMarker(events[outputTrack]); } } if (settings.RecreateEndTrackMarkers) { if (outputFileType == 1) { // if we are converting type 0 to type 1 and recreating end markers, if (midiFile.FileFormat == 0) { AppendEndMarker(events[1]); } } // make sure that track zero has an end track marker AppendEndMarker(events[0]); } else { // if we are converting type 0 to type 1 without recreating end markers, // then we still need to add an end marker to track 1 if (midiFile.FileFormat == 0) { // use the time we got from track 0 as the end track time for track 1 if (endTrackTime == -1) { LogError("Error adding track 1 end marker"); // make it a valid MIDI file anyway AppendEndMarker(events[1]); } else { events[1].Add(new MetaEvent(MetaEventType.EndTrack, 0, endTrackTime)); } } } if (settings.VerboseOutput) { LogTrace("Processing {0}: {1}", name, target); } if (settings.RemoveEmptyTracks) { MidiEventCollection newList = new MidiEventCollection(events.MidiFileType, events.DeltaTicksPerQuarterNote); int removed = 0; for (int track = 0; track < events.Tracks; track++) { IList<MidiEvent> trackEvents = events[track]; if (track < 2) { newList.AddTrack(events[track]); } else { if(HasNotes(trackEvents)) { newList.AddTrack(trackEvents); } else { removed++; } } } if (removed > 0) { events = newList; LogWarning("Removed {0} empty tracks from {1} ({2} remain)", removed, target, events.Tracks); } } MidiFile.Export(target, events); }
void txtOpenMidi_ClickText(ClickableText clickableText, MouseState mouseState, GameTime gameTime) { //D:\Log\geff\TheGrid\TheGrid\TheGrid\Files\Sound\Midi\MozartTurque.mid //@"D:\Libraries\Musics\Midi\beethoven-pour-elise.mid" //D:\Log\geff\TheGrid\TheGrid\TheGrid\Files\Sound\Midi\Vivaldi4SeasWint.mid NAudio.Midi.MidiFile midiFile = new MidiFile(@"D:\Geff\Log\geff\TheGrid\TheGrid\TheGrid\Files\Sound\Midi\beethoven-pour-elise.mid"); //NAudio.Midi.MidiFile midiFile = new MidiFile(@"D:\GDD\Log\Geff\TheGrid\TheGrid\TheGrid\Files\Sound\Midi\beethoven-pour-elise.mid"); //if (midiFile != null) //{ // foreach (MidiEvent midiEvent in midiFile.Events[2]) // { // NoteEvent noteEvent = midiEvent as NoteEvent; // if (noteEvent != null && noteEvent.CommandCode== MidiCommandCode.NoteOn) // { // AddNote(noteEvent.NoteNumber - 20, noteEvent.NoteName); // } // } //} NoteOnEvent prevNoteEvent = null; int prevNoteLength = 1; int noteLength = 1; if (midiFile != null) { for (int i = 0; i < midiFile.Tracks; i++) { foreach (MidiEvent midiEvent in midiFile.Events[i]) { NoteOnEvent noteEvent = midiEvent as NoteOnEvent; if (noteEvent != null && noteEvent.CommandCode == MidiCommandCode.NoteOn) { try { noteLength = noteEvent.NoteLength; } catch { } float typeNote = (float)noteLength / (float)midiFile.DeltaTicksPerQuarterNote; //--- Ajout des silences if (prevNoteEvent != null) { float deltaTime = noteEvent.AbsoluteTime - (prevNoteEvent.AbsoluteTime + prevNoteLength); int countQuarterNote = (int)(deltaTime / (float)midiFile.DeltaTicksPerQuarterNote); if (deltaTime > midiFile.DeltaTicksPerQuarterNote) { for (int j = 1; j <= countQuarterNote ; j++) { AddSilence(1f, Sample.Channel); } } if (deltaTime > countQuarterNote*midiFile.DeltaTicksPerQuarterNote) { typeNote = (deltaTime - countQuarterNote * midiFile.DeltaTicksPerQuarterNote) / (float)midiFile.DeltaTicksPerQuarterNote; AddSilence(typeNote, Sample.Channel); } } //--- //--- Ajout de la note AddNote(noteEvent.NoteNumber - 20, typeNote, noteEvent.NoteName); //--- } if (noteEvent != null) { prevNoteEvent = noteEvent; prevNoteLength = noteLength; } } } } }