/// <summary> /// It's an optional action before playing a midi file witk MPTK_Play. /// Useful to get information (duration, ...) before playing the Midi. /// </summary> private void GetMidiInfo() { MidiLoad midiloaded = midiFilePlayer.MPTK_Load(); if (midiloaded != null) { infoMidi = "Duration: " + midiloaded.MPTK_Duration.TotalSeconds + " seconds\n"; infoMidi += "Tempo: " + midiloaded.MPTK_InitialTempo + "\n"; List <MPTKEvent> listEvents = midiloaded.MPTK_ReadMidiEvents(); infoMidi += "Count Midi Events: " + listEvents.Count + "\n"; Debug.Log(infoMidi); } }
/// <summary> /// It's an optional action before playing a midi file witk MPTK_Play. /// Useful to get information (duration, ...) before playing the Midi. /// </summary> private void GetMidiInfo() { MidiLoad midiloaded = midiFilePlayer.MPTK_Load(); if (midiloaded != null) { infoMidi = string.Format("Duration : {0}\n", midiloaded.MPTK_Duration); infoMidi += string.Format("Real Duration: {0}\n", midiloaded.MPTK_RealDuration); infoMidi += "Tempo: " + Mathf.RoundToInt((float)midiloaded.MPTK_InitialTempo) + "\n"; List <MPTKEvent> listEvents = midiloaded.MPTK_ReadMidiEvents(); infoMidi += "Count Midi Events: " + listEvents.Count + "\n"; //Debug.Log(infoMidi); } }
private void MidiChanged(object tag, int midiindex) { Debug.Log("MidiChanged " + midiindex); MidiIndex = midiindex; MidiLoaded = new MidiLoad(); //MidiLoaded.LogEvents = true; //MidiLoaded.MPTK_Load("Beattles - Michelle"); MidiLoaded.MPTK_Load(midiindex); StartTicks = 0; EndTicks = MidiLoaded.MPTK_TickLast; PageToDisplay = 0; scrollPos = new Vector2(0, 0); infoEvents = new List <string>(); }
/// <summary> /// Load the midi file defined with MPTK_MidiName or MPTK_MidiIndex or from a array of bytes /// </summary> /// <param name="midiBytesToLoad"></param> public void MPTK_Load(byte[] midiBytesToLoad = null) { try { // Load description of available soundfont //if (MidiPlayerGlobal.ImSFCurrent != null && MidiPlayerGlobal.CurrentMidiSet != null && MidiPlayerGlobal.CurrentMidiSet.MidiFiles != null && MidiPlayerGlobal.CurrentMidiSet.MidiFiles.Count > 0) { if (string.IsNullOrEmpty(MPTK_MidiName)) { MPTK_MidiName = MidiPlayerGlobal.CurrentMidiSet.MidiFiles[0]; } int selectedMidi = MidiPlayerGlobal.CurrentMidiSet.MidiFiles.FindIndex(s => s == MPTK_MidiName); if (selectedMidi < 0) { Debug.LogWarning("MidiFilePlayer - MidiFile " + MPTK_MidiName + " not found. Try with the first in list."); selectedMidi = 0; MPTK_MidiName = MidiPlayerGlobal.CurrentMidiSet.MidiFiles[0]; } try { miditoload = new MidiLoad(); // No midi byte array, try to load from MidiFile from resource if (midiBytesToLoad == null || midiBytesToLoad.Length == 0) { TextAsset mididata = Resources.Load <TextAsset>(System.IO.Path.Combine(MidiPlayerGlobal.MidiFilesDB, MPTK_MidiName)); midiBytesToLoad = mididata.bytes; } miditoload.KeepNoteOff = MPTK_KeepNoteOff; miditoload.EnableChangeTempo = MPTK_EnableChangeTempo; miditoload.MPTK_Load(midiBytesToLoad); SetAttributes(); } catch (System.Exception ex) { MidiPlayerGlobal.ErrorDetail(ex); } } //else // Debug.LogWarning(MidiPlayerGlobal.ErrorNoMidiFile); } catch (System.Exception ex) { MidiPlayerGlobal.ErrorDetail(ex); } }
/// <summary> /// Load the midi file defined with MPTK_MidiName or MPTK_MidiIndex. It's an optional action before playing a midi file witk MPTK_Play. ///! @code /// private void GetMidiInfo() /// { /// MidiLoad midiloaded = midiFilePlayer.MPTK_Load(); /// if (midiloaded != null) /// { /// infoMidi = "Duration: " + midiloaded.MPTK_Duration.TotalSeconds + " seconds\n"; /// infoMidi += "Tempo: " + midiloaded.MPTK_InitialTempo + "\n"; /// List<MPTKEvent> listEvents = midiloaded.MPTK_ReadMidiEvents(); /// infoMidi += "Count Midi Events: " + listEvents.Count + "\n"; /// Debug.Log(infoMidi); /// } /// } ///! @endcode /// </summary> /// <returns>MidiLoad to access all the properties of the midi loaded</returns> public MidiLoad MPTK_Load() { MidiLoad miditoload = new MidiLoad(); if (string.IsNullOrEmpty(MPTK_MidiName)) { Debug.LogWarning("MPTK_Load: midi name not defined"); return(null); } TextAsset mididata = Resources.Load <TextAsset>(Path.Combine(MidiPlayerGlobal.MidiFilesDB, MPTK_MidiName)); if (mididata == null || mididata.bytes == null || mididata.bytes.Length == 0) { Debug.LogWarning("MPTK_Load: error when loading midi " + MPTK_MidiName); return(null); } miditoload.KeepNoteOff = false; miditoload.MPTK_Load(mididata.bytes); return(miditoload); }
protected IEnumerator <float> ThreadPlay(byte[] midiBytesToPlay = null) { midiIsPlaying = true; stopMidi = false; replayMidi = false; bool first = true; string currentMidiName = ""; //Debug.Log("Start play"); try { miditoplay = new MidiLoad(); // No midi byte array, try to load from MidiFilesDN from resource if (midiBytesToPlay == null || midiBytesToPlay.Length == 0) { currentMidiName = MPTK_MidiName; TextAsset mididata = Resources.Load <TextAsset>(Path.Combine(MidiPlayerGlobal.MidiFilesDB, currentMidiName)); midiBytesToPlay = mididata.bytes; } miditoplay.KeepNoteOff = MPTK_KeepNoteOff; miditoplay.MPTK_Load(midiBytesToPlay); } catch (System.Exception ex) { MidiPlayerGlobal.ErrorDetail(ex); } if (miditoplay != null) { yield return(Timing.WaitUntilDone(Timing.RunCoroutine(ThreadClearAllSound(true)), false)); try { OnEventStartPlayMidi.Invoke(currentMidiName); } catch (System.Exception ex) { MidiPlayerGlobal.ErrorDetail(ex); } try { miditoplay.ChangeSpeed(MPTK_Speed); miditoplay.ChangeQuantization(MPTK_Quantization); } catch (System.Exception ex) { MidiPlayerGlobal.ErrorDetail(ex); } lastTimePlay = Time.realtimeSinceStartup; timeFromStartPlay = 0d; // Loop on each events midi do { miditoplay.LogEvents = MPTK_LogEvents; if (MPTK_PauseOnDistance) { distanceEditorModeOnly = MidiPlayerGlobal.MPTK_DistanceToListener(this.transform); if (distanceEditorModeOnly > VoiceTemplate.Audiosource.maxDistance) { lastTimePlay = Time.realtimeSinceStartup; yield return(Timing.WaitForSeconds(0.2f)); continue; } } if (playPause) { lastTimePlay = Time.realtimeSinceStartup; yield return(Timing.WaitForSeconds(0.2f)); if (miditoplay.EndMidiEvent || replayMidi || stopMidi) { break; } if (timeToPauseMilliSeconde > -1f) { timeToPauseMilliSeconde -= 0.2f; if (timeToPauseMilliSeconde <= 0f) { playPause = false; } } continue; } if (!first) { timeFromStartPlay += (Time.realtimeSinceStartup - lastTimePlay) * 1000d; } else { timeFromStartPlay = 0d; first = false; } //Debug.Log("---------------- " + timeFromStartPlay ); // Read midi events until this time List <MPTKEvent> midievents = miditoplay.ReadMidiEvents(timeFromStartPlay); if (miditoplay.EndMidiEvent || replayMidi || stopMidi) { break; } // Play notes read if (midievents != null && midievents.Count > 0) { try { if (OnEventNotesMidi != null) { OnEventNotesMidi.Invoke(midievents); } } catch (System.Exception ex) { MidiPlayerGlobal.ErrorDetail(ex); } //float beforePLay = Time.realtimeSinceStartup; //Debug.Log("---------------- play count:" + midievents.Count + " Start:" + timeFromStartPlay + " Delta:" + (Time.realtimeSinceStartup - lastTimePlay) * 1000f); if (MPTK_DirectSendToPlayer) { foreach (MPTKEvent midievent in midievents) { if (midievent.Command == MPTKCommand.MetaEvent && midievent.Meta == MPTKMeta.SetTempo && MPTK_EnableChangeTempo) { miditoplay.ChangeTempo(midievent.Duration); //Debug.Log(BuildInfoTrack(trackEvent) + string.Format("SetTempo {0} MicrosecondsPerQuarterNote:{1}", tempo.Tempo, tempo.MicrosecondsPerQuarterNote)); } else { PlayEvent(midievent); } } } //Debug.Log("---------------- played count:" + notes.Count + " Start:" + timeFromStartPlay + " Delta:" + (Time.realtimeSinceStartup - lastTimePlay) * 1000f + " Elapsed:" + (Time.realtimeSinceStartup - beforePLay) * 1000f); } lastTimePlay = Time.realtimeSinceStartup; if (Application.isEditor) { TimeSpan times = TimeSpan.FromMilliseconds(timeFromStartPlay); playTimeEditorModeOnly = string.Format("{0:00}:{1:00}:{2:00}:{3:000}", times.Hours, times.Minutes, times.Seconds, times.Milliseconds); durationEditorModeOnly = string.Format("{0:00}:{1:00}:{2:00}:{3:000}", MPTK_Duration.Hours, MPTK_Duration.Minutes, MPTK_Duration.Seconds, MPTK_Duration.Milliseconds); } yield return(-1);// new WaitForSeconds(delayMilliSeconde / 1000f);// 0.01f); }while (true); } else { Debug.LogWarning("MidiFilePlayer/ThreadPlay - Midi Load error"); } midiIsPlaying = false; try { EventEndMidiEnum reason = EventEndMidiEnum.MidiEnd; if (nextMidi) { reason = EventEndMidiEnum.Next; nextMidi = false; } else if (prevMidi) { reason = EventEndMidiEnum.Previous; prevMidi = false; } else if (stopMidi) { reason = EventEndMidiEnum.ApiStop; } else if (replayMidi) { reason = EventEndMidiEnum.Replay; } OnEventEndPlayMidi.Invoke(currentMidiName, reason); if ((MPTK_Loop || replayMidi) && !stopMidi) { MPTK_Play(); } //stopMidiToPlay = false; } catch (System.Exception ex) { MidiPlayerGlobal.ErrorDetail(ex); } //Debug.Log("Stop play"); }
/// <summary> /// Return information about a midifile : patch change, copyright, ... /// </summary> /// <param name="pathfilename"></param> /// <param name="Info"></param> static public List <string> GeneralInfo(string pathfilename, bool withNoteOn, bool withNoteOff, bool withControlChange, bool withPatchChange, bool withAfterTouch, bool withMeta, bool withOthers) { List <string> Info = new List <string>(); try { int NumberBeatsMeasure; int NumberQuarterBeat; MidiLoad midifile = new MidiLoad(); midifile.KeepNoteOff = withNoteOff; midifile.MPTK_Load(pathfilename); if (midifile != null) { Info.Add(string.Format("Format: {0}", midifile.midifile.FileFormat)); Info.Add(string.Format("Tracks: {0}", midifile.midifile.Tracks)); Info.Add(string.Format("Events count: {0}", midifile.MidiSorted.Count())); Info.Add(string.Format("Duration: {0} ({1} seconds) {2} Ticks", midifile.MPTK_RealDuration, midifile.MPTK_RealDuration.TotalSeconds, midifile.MPTK_TickLast)); Info.Add(string.Format("Initial Tempo: {0,0:F2} BPM", midifile.MPTK_InitialTempo)); Info.Add(string.Format("Beats in a measure: {0}", midifile.MPTK_NumberBeatsMeasure)); Info.Add(string.Format("Quarters count in a beat:{0}", midifile.MPTK_NumberQuarterBeat)); Info.Add(string.Format("Ticks per Quarter Note: {0}", midifile.midifile.DeltaTicksPerQuarterNote)); Info.Add(""); //if (false) { foreach (TrackMidiEvent trackEvent in midifile.MidiSorted) { switch (trackEvent.Event.CommandCode) { case MidiCommandCode.NoteOn: if (withNoteOn) { if (((NoteOnEvent)trackEvent.Event).OffEvent != null) { NoteOnEvent noteon = (NoteOnEvent)trackEvent.Event; Info.Add(BuildInfoTrack(trackEvent) + string.Format("NoteOn {0,3} ({1,3}) Len:{2,3} Vel:{3,3}", noteon.NoteName, noteon.NoteNumber, noteon.NoteLength, noteon.Velocity)); } } break; case MidiCommandCode.NoteOff: if (withNoteOff) { NoteEvent noteoff = (NoteEvent)trackEvent.Event; Info.Add(BuildInfoTrack(trackEvent) + string.Format("NoteOff {0,3} ({1,3}) Vel:{2,3}", noteoff.NoteName, noteoff.NoteNumber, noteoff.Velocity)); } break; case MidiCommandCode.PitchWheelChange: if (withOthers) { PitchWheelChangeEvent aftertouch = (PitchWheelChangeEvent)trackEvent.Event; Info.Add(BuildInfoTrack(trackEvent) + string.Format("PitchWheelChange {0,3}", aftertouch.Pitch)); } break; case MidiCommandCode.KeyAfterTouch: if (withAfterTouch) { NoteEvent aftertouch = (NoteEvent)trackEvent.Event; Info.Add(BuildInfoTrack(trackEvent) + string.Format("KeyAfterTouch {0,3} ({1,3}) Pressure:{2,3}", aftertouch.NoteName, aftertouch.NoteNumber, aftertouch.Velocity)); } break; case MidiCommandCode.ChannelAfterTouch: if (withAfterTouch) { ChannelAfterTouchEvent aftertouch = (ChannelAfterTouchEvent)trackEvent.Event; Info.Add(BuildInfoTrack(trackEvent) + string.Format("ChannelAfterTouch Pressure:{0,3}", aftertouch.AfterTouchPressure)); } break; case MidiCommandCode.ControlChange: if (withControlChange) { ControlChangeEvent controlchange = (ControlChangeEvent)trackEvent.Event; Info.Add(BuildInfoTrack(trackEvent) + string.Format("ControlChange {0,3} ({1,3}) Value:{2,3}", controlchange.Controller, controlchange.Controller, controlchange.ControllerValue)); } break; case MidiCommandCode.PatchChange: if (withPatchChange) { PatchChangeEvent change = (PatchChangeEvent)trackEvent.Event; Info.Add(BuildInfoTrack(trackEvent) + string.Format("PatchChange {0,3:000} {1}", change.Patch, PatchChangeEvent.GetPatchName(change.Patch))); } break; case MidiCommandCode.MetaEvent: if (withMeta) { MetaEvent meta = (MetaEvent)trackEvent.Event; switch (meta.MetaEventType) { case MetaEventType.SetTempo: TempoEvent tempo = (TempoEvent)meta; Info.Add(BuildInfoTrack(trackEvent) + string.Format("SetTempo Tempo:{0} MicrosecondsPerQuarterNote:{1}", Math.Round(tempo.Tempo, 0), tempo.MicrosecondsPerQuarterNote)); //tempo.Tempo break; case MetaEventType.TimeSignature: TimeSignatureEvent timesig = (TimeSignatureEvent)meta; // Numerator: counts the number of beats in a measure. // For example a numerator of 4 means that each bar contains four beats. // Denominator: number of quarter notes in a beat.0=ronde, 1=blanche, 2=quarter, 3=eighth, etc. // Set default value NumberBeatsMeasure = timesig.Numerator; NumberQuarterBeat = System.Convert.ToInt32(Mathf.Pow(2, timesig.Denominator)); Info.Add(BuildInfoTrack(trackEvent) + string.Format("TimeSignature Beats Measure:{0} Beat Quarter:{1}", NumberBeatsMeasure, NumberQuarterBeat)); break; default: string text = meta is TextEvent ? " '" + ((TextEvent)meta).Text + "'" : ""; Info.Add(BuildInfoTrack(trackEvent) + meta.MetaEventType.ToString() + text); break; } } break; default: // Other midi event if (withOthers) { Info.Add(BuildInfoTrack(trackEvent) + string.Format(" {0} ({1})", trackEvent.Event.CommandCode, (int)trackEvent.Event.CommandCode)); } break; } } } //else DebugMidiSorted(midifile.MidiSorted); } else { Info.Add("Error reading midi file"); } } catch (System.Exception ex) { MidiPlayerGlobal.ErrorDetail(ex); } return(Info); }
protected IEnumerator ThreadPlay(byte[] midibytestoplay = null) { midiIsPlaying = true; stopMidiToPlay = false; newMidiToPlay = false; bool first = true; //Debug.Log("Start play"); try { miditoplay = new MidiLoad(); // No midi byte array, try to load from MidiFilesDN from resource if (midibytestoplay == null || midibytestoplay.Length == 0) { TextAsset mididata = Resources.Load <TextAsset>(Path.Combine(MidiPlayerGlobal.MidiFilesDB, MPTK_MidiName)); midibytestoplay = mididata.bytes; } miditoplay.KeepNoteOff = MPTK_KeepNoteOff; miditoplay.Load(midibytestoplay); } catch (System.Exception ex) { MidiPlayerGlobal.ErrorDetail(ex); } if (miditoplay != null) { yield return(StartCoroutine(MPTK_ClearAllSound(true))); try { OnEventStartPlayMidi.Invoke(); } catch (System.Exception ex) { MidiPlayerGlobal.ErrorDetail(ex); } try { miditoplay.ChangeSpeed(MPTK_Speed); miditoplay.ChangeQuantization(MPTK_Quantization); } catch (System.Exception ex) { MidiPlayerGlobal.ErrorDetail(ex); } lastTimePlay = Time.realtimeSinceStartup; timeFromStartPlay = 0d; // Loop on each events midi do { miditoplay.LogEvents = MPTK_LogEvents; miditoplay.EnableChangeTempo = MPTK_EnableChangeTempo; miditoplay.EnablePanChange = MPTK_EnablePanChange; if (MPTK_PauseOnDistance) { distanceEditorModeOnly = MidiPlayerGlobal.MPTK_DistanceToListener(this.transform); if (distanceEditorModeOnly > AudioSourceTemplate.maxDistance) { lastTimePlay = Time.realtimeSinceStartup; yield return(new WaitForSeconds(0.2f)); continue; } } if (playPause) { lastTimePlay = Time.realtimeSinceStartup; yield return(new WaitForSeconds(0.2f)); if (miditoplay.EndMidiEvent || newMidiToPlay || stopMidiToPlay) { break; } if (timeToPauseMilliSeconde > -1f) { timeToPauseMilliSeconde -= 0.2f; if (timeToPauseMilliSeconde <= 0f) { playPause = false; } } continue; } if (!first) { timeFromStartPlay += (Time.realtimeSinceStartup - lastTimePlay) * 1000f; } else { timeFromStartPlay = 0d; first = false; } lastTimePlay = Time.realtimeSinceStartup; //Debug.Log("---------------- " + timeFromStartPlay ); // Read midi events until this time List <MidiNote> notes = miditoplay.ReadMidiEvents(timeFromStartPlay); if (miditoplay.EndMidiEvent || newMidiToPlay || stopMidiToPlay) { break; } // Play notes read if (notes != null && notes.Count > 0) { try { if (OnEventNotesMidi != null) { OnEventNotesMidi.Invoke(notes); } } catch (System.Exception ex) { MidiPlayerGlobal.ErrorDetail(ex); } if (MPTK_DirectSendToPlayer) { MPTK_PlayNotes(notes); } //Debug.Log("---------------- play count:" + notes.Count + " " + timeFromStartMS ); } if (Application.isEditor) { TimeSpan times = TimeSpan.FromMilliseconds(timeFromStartPlay); playTimeEditorModeOnly = string.Format("{0:00}:{1:00}:{2:00}:{3:000}", times.Hours, times.Minutes, times.Seconds, times.Milliseconds); durationEditorModeOnly = string.Format("{0:00}:{1:00}:{2:00}:{3:000}", MPTK_Duration.Hours, MPTK_Duration.Minutes, MPTK_Duration.Seconds, MPTK_Duration.Milliseconds); } yield return(new WaitForSeconds(delayMilliSeconde / 1000f));// 0.01f); }while (true); } midiIsPlaying = false; try { if (OnEventEndPlayMidi != null && !stopMidiToPlay && !newMidiToPlay) { OnEventEndPlayMidi.Invoke(); } if ((MPTK_Loop || newMidiToPlay) && !stopMidiToPlay) { MPTK_Play(); } //stopMidiToPlay = false; } catch (System.Exception ex) { MidiPlayerGlobal.ErrorDetail(ex); } //Debug.Log("Stop play"); }
/// <summary> /// Return information about a midifile : patch change, copyright, ... /// </summary> /// <param name="pathfilename"></param> /// <param name="Info"></param> static public void GeneralInfo(string pathfilename, BuilderInfo Info) { try { int NumberBeatsMeasure; int NumberQuarterBeat; Debug.Log("Open midifile :" + pathfilename); MidiLoad midifile = new MidiLoad(); midifile.MPTK_Load(pathfilename); if (midifile != null) { Info.Add(string.Format("Format: {0}", midifile.midifile.FileFormat)); Info.Add(string.Format("Tracks: {0}", midifile.midifile.Tracks)); Info.Add(string.Format("Ticks Quarter Note: {0}", midifile.midifile.DeltaTicksPerQuarterNote)); //if (false) { foreach (TrackMidiEvent trackEvent in midifile.MidiSorted) { if (trackEvent.Event.CommandCode == MidiCommandCode.NoteOn) { // Not used //if (((NoteOnEvent)trackEvent.Event).OffEvent != null) //{ // //infoTrackMidi[e.Channel].Events.Add((NoteOnEvent)e); // NoteOnEvent noteon = (NoteOnEvent)trackEvent.Event; //} } else if (trackEvent.Event.CommandCode == MidiCommandCode.NoteOff) { //Debug.Log("NoteOff"); } else if (trackEvent.Event.CommandCode == MidiCommandCode.ControlChange) { // Not used //ControlChangeEvent controlchange = (ControlChangeEvent)e; //Debug.Log(string.Format("CtrlChange Track:{0} Channel:{1,2:00} {2}", track, e.Channel, controlchange.ToString())); } else if (trackEvent.Event.CommandCode == MidiCommandCode.PatchChange) { PatchChangeEvent change = (PatchChangeEvent)trackEvent.Event; Info.Add(BuildInfoTrack(trackEvent) + string.Format("PatchChange {0,3:000} {1}", change.Patch, PatchChangeEvent.GetPatchName(change.Patch)), 2); } else if (trackEvent.Event.CommandCode == MidiCommandCode.MetaEvent) { MetaEvent meta = (MetaEvent)trackEvent.Event; switch (meta.MetaEventType) { case MetaEventType.SetTempo: TempoEvent tempo = (TempoEvent)meta; Info.Add(BuildInfoTrack(trackEvent) + string.Format("SetTempo Tempo:{0} MicrosecondsPerQuarterNote:{1}", Math.Round(tempo.Tempo, 0), tempo.MicrosecondsPerQuarterNote), 2); //tempo.Tempo break; case MetaEventType.TimeSignature: TimeSignatureEvent timesig = (TimeSignatureEvent)meta; // Numerator: counts the number of beats in a measure. // For example a numerator of 4 means that each bar contains four beats. // Denominator: number of quarter notes in a beat.0=ronde, 1=blanche, 2=quarter, 3=eighth, etc. // Set default value NumberBeatsMeasure = timesig.Numerator; NumberQuarterBeat = System.Convert.ToInt32(System.Math.Pow(2, timesig.Denominator)); Info.Add(BuildInfoTrack(trackEvent) + string.Format("TimeSignature Beats Measure:{0} Beat Quarter:{1}", NumberBeatsMeasure, NumberQuarterBeat), 2); break; case MetaEventType.SequenceTrackName: // Sequence / Track Name case MetaEventType.ProgramName: case MetaEventType.TrackInstrumentName: // Track instrument name case MetaEventType.TextEvent: // Text event case MetaEventType.Copyright: // Copyright Info.Add(BuildInfoTrack(trackEvent) + ((TextEvent)meta).Text, 1); break; case MetaEventType.Lyric: // lyric case MetaEventType.Marker: // marker case MetaEventType.CuePoint: // cue point case MetaEventType.DeviceName: //Info.Add(BuildInfoTrack(trackEvent) + string.Format("{0} '{1}'", meta.MetaEventType.ToString(), ((TextEvent)meta).Text)); break; } } else { // Other midi event //Debug.Log(string.Format("Track:{0} Channel:{1,2:00} CommandCode:{2,3:000} AbsoluteTime:{3,6:000000}", track, e.Channel, e.CommandCode.ToString(), e.AbsoluteTime)); } } } //else DebugMidiSorted(midifile.MidiSorted); } else { Info.Add("Error reading midi file"); } } catch (System.Exception ex) { MidiPlayerGlobal.ErrorDetail(ex); } }
/// <summary> /// Display, add, remove Midi file /// </summary> /// <param name="localstartX"></param> /// <param name="localstartY"></param> private void ShowListMidiFiles(float localstartX, float localstartY) { try { Rect zone = new Rect(localstartX, localstartY, widthLeft, heightList); GUI.color = new Color(.8f, .8f, .8f, 1f); GUI.Box(zone, ""); GUI.color = Color.white; string caption = "Midi file available"; if (MidiPlayerGlobal.CurrentMidiSet.MidiFiles == null || MidiPlayerGlobal.CurrentMidiSet.MidiFiles.Count == 0) { caption = "No Midi file available yet"; ScanInfo = new BuilderInfo(); } GUIContent content = new GUIContent() { text = caption, tooltip = "" }; EditorGUI.LabelField(new Rect(localstartX + xpostitlebox, localstartY + ypostitlebox, 300, itemHeight), content, styleBold); if (GUI.Button(new Rect(widthLeft - buttonWidth - espace, localstartY + ypostitlebox, buttonWidth, buttonHeight), "Add Midi file")) { AddMidifile(); } if (MidiPlayerGlobal.CurrentMidiSet.MidiFiles != null) { Rect listVisibleRect = new Rect(localstartX, localstartY + itemHeight, widthLeft - 5, heightList - itemHeight - 5); Rect listContentRect = new Rect(0, 0, widthLeft - 20, MidiPlayerGlobal.CurrentMidiSet.MidiFiles.Count * itemHeight + 5); scrollPosMidiFile = GUI.BeginScrollView(listVisibleRect, scrollPosMidiFile, listContentRect); float boxY = 0; for (int i = 0; i < MidiPlayerGlobal.CurrentMidiSet.MidiFiles.Count; i++) { GUI.color = new Color(.7f, .7f, .7f, 1f); float boxX = 5; GUI.Box(new Rect(boxX, boxY + 5, widthLeft - 30, itemHeight), ""); GUI.color = Color.white; content = new GUIContent() { text = i.ToString() + " - " + MidiPlayerGlobal.CurrentMidiSet.MidiFiles[i], tooltip = MidiPlayerGlobal.CurrentMidiSet.MidiFiles[i] }; EditorGUI.LabelField(new Rect(boxX, boxY + 9, 200, itemHeight), content); boxX += 285 + espace; if (GUI.Button(new Rect(boxX, boxY + 9, 80, buttonHeight), "Analyse")) { ScanInfo = new BuilderInfo(); midifile = MidiPlayerGlobal.CurrentMidiSet.MidiFiles[i]; ScanInfo.Add(midifile); MidiScan.GeneralInfo(midifile, ScanInfo); scrollPosAnalyze = Vector2.zero; } boxX += 80 + espace; GUI.color = Color.white; if (GUI.Button(new Rect(boxX, boxY + 9, 80, buttonHeight), "Remove")) { if (!string.IsNullOrEmpty(MidiPlayerGlobal.CurrentMidiSet.MidiFiles[i])) { DeleteResource(MidiLoad.BuildOSPath(MidiPlayerGlobal.CurrentMidiSet.MidiFiles[i])); AssetDatabase.Refresh(); ToolsEditor.CheckMidiSet(); } } boxY += itemHeight; } GUI.EndScrollView(); } } catch (Exception ex) { MidiPlayerGlobal.ErrorDetail(ex); } }
/// <summary> /// Add a new Midi file from desktop /// </summary> private static void AddMidifile() { try { string selectedFile = EditorUtility.OpenFilePanelWithFilters("Open and import Midi file", ToolsEditor.lastDirectoryMidi, new string[] { "Midi files", "mid,midi", "Karoke files", "kar", "All", "*" }); if (!string.IsNullOrEmpty(selectedFile)) { ToolsEditor.lastDirectoryMidi = Path.GetDirectoryName(selectedFile); // Build path to midi folder string pathMidiFile = Path.Combine(Application.dataPath, MidiPlayerGlobal.PathToMidiFile); if (!Directory.Exists(pathMidiFile)) { Directory.CreateDirectory(pathMidiFile); } try { MidiLoad midifile = new MidiLoad(); if (!midifile.MPTK_LoadFile(selectedFile)) { EditorUtility.DisplayDialog("Midi Not Loaded", "Try to open " + selectedFile + "\nbut this file is not a valid midi file", "ok"); return; } } catch (Exception ex) { Debug.LogWarningFormat("{0} {1}", selectedFile, ex.Message); return; } string filename = Path.GetFileNameWithoutExtension(selectedFile); //foreach (char c in filename) Debug.Log(string.Format("{0} {1}", c, (int)c)); foreach (char i in Path.GetInvalidFileNameChars()) { filename = filename.Replace(i, '_'); } string filenameToSave = Path.Combine(pathMidiFile, filename + MidiPlayerGlobal.ExtensionMidiFile); filenameToSave = filenameToSave.Replace('(', '_'); filenameToSave = filenameToSave.Replace(')', '_'); filenameToSave = filenameToSave.Replace('#', '_'); filenameToSave = filenameToSave.Replace('$', '_'); // Create a copy of the midi file in MPTK resources File.Copy(selectedFile, filenameToSave, true); if (MidiPlayerGlobal.CurrentMidiSet.MidiFiles == null) { MidiPlayerGlobal.CurrentMidiSet.MidiFiles = new List <string>(); } // Add midi file to the list string midiname = Path.GetFileNameWithoutExtension(selectedFile); if (MidiPlayerGlobal.CurrentMidiSet.MidiFiles.FindIndex(s => s == midiname) < 0) { MidiPlayerGlobal.CurrentMidiSet.MidiFiles.Add(midiname); MidiPlayerGlobal.CurrentMidiSet.MidiFiles.Sort(); MidiPlayerGlobal.CurrentMidiSet.Save(); } indexEditItem = MidiPlayerGlobal.CurrentMidiSet.MidiFiles.FindIndex(s => s == midiname); } AssetDatabase.Refresh(); ToolsEditor.LoadMidiSet(); ToolsEditor.CheckMidiSet(); AssetDatabase.Refresh(); ReadEvents(); } catch (System.Exception ex) { MidiPlayerGlobal.ErrorDetail(ex); } }
/// <summary> /// Display, add, remove Midi file /// </summary> /// <param name="localstartX"></param> /// <param name="localstartY"></param> private void ShowListMidiFiles(float localstartX, float localstartY) { try { Rect zone = new Rect(localstartX, localstartY, widthLeft, heightList); GUI.color = new Color(.8f, .8f, .8f, 1f); GUI.Box(zone, ""); GUI.color = Color.white; string caption = "Midi file available"; if (MidiPlayerGlobal.CurrentMidiSet.MidiFiles == null || MidiPlayerGlobal.CurrentMidiSet.MidiFiles.Count == 0) { caption = "No Midi file available yet"; } GUIContent content = new GUIContent() { text = caption, tooltip = "" }; EditorGUI.LabelField(new Rect(localstartX + xpostitlebox, localstartY + ypostitlebox, 300, itemHeight), content, styleBold); if (indexEditItem >= 0 && indexEditItem < MidiPlayerGlobal.CurrentMidiSet.MidiFiles.Count && !string.IsNullOrEmpty(MidiPlayerGlobal.CurrentMidiSet.MidiFiles[indexEditItem])) { string name = MidiPlayerGlobal.CurrentMidiSet.MidiFiles[indexEditItem]; if (name.Length > 10) { name = name.Substring(0, 10); } string midiselected = "'" + indexEditItem + "-" + name + "'"; if (GUI.Button(new Rect(localstartX + xpostitlebox + 150, localstartY + ypostitlebox, buttonWidth, buttonHeight), "Remove " + midiselected)) { DeleteResource(MidiLoad.BuildOSPath(MidiPlayerGlobal.CurrentMidiSet.MidiFiles[indexEditItem])); AssetDatabase.Refresh(); ToolsEditor.LoadMidiSet(); ToolsEditor.CheckMidiSet(); AssetDatabase.Refresh(); } } if (GUI.Button(new Rect(widthLeft - buttonWidth - espace, localstartY + ypostitlebox, buttonWidth, buttonHeight), "Add Midi file")) { AddMidifile(); } if (MidiPlayerGlobal.CurrentMidiSet.MidiFiles != null) { Rect listVisibleRect = new Rect(localstartX, localstartY + itemHeight, widthLeft - 5, heightList - itemHeight - 5); Rect listContentRect = new Rect(0, 0, widthLeft - 20, MidiPlayerGlobal.CurrentMidiSet.MidiFiles.Count * itemHeight + 5); scrollPosMidiFile = GUI.BeginScrollView(listVisibleRect, scrollPosMidiFile, listContentRect); float boxY = 0; for (int i = 0; i < MidiPlayerGlobal.CurrentMidiSet.MidiFiles.Count; i++) { //GUI.color = new Color(.7f, .7f, .7f, 1f); float boxX = 5; content = new GUIContent() { text = i.ToString() + " - " + MidiPlayerGlobal.CurrentMidiSet.MidiFiles[i], tooltip = MidiPlayerGlobal.CurrentMidiSet.MidiFiles[i] }; if (indexEditItem == i) { GUI.color = new Color(.7f, .7f, .7f, 1f); } else { GUI.color = Color.white; } GUI.Box(new Rect(boxX, boxY + 5, widthLeft - 30, itemHeight), ""); if (GUI.Button(new Rect(boxX + 5, boxY + 9, widthLeft - 30, itemHeight), content, myStyle.BtListNormal)) { indexEditItem = i; ReadEvents(); } boxY += itemHeight; } GUI.EndScrollView(); } } catch (Exception ex) { MidiPlayerGlobal.ErrorDetail(ex); } }
/// <summary> /// Display, add, remove Midi file /// </summary> /// <param name="startX"></param> /// <param name="startY"></param> private void ShowListMidiFiles(float startX, float startY, float width, float height) { try { Event e = Event.current; if (e.type == EventType.KeyDown) { //Debug.Log("Ev.KeyDown: " + e); if (e.keyCode == KeyCode.DownArrow || e.keyCode == KeyCode.UpArrow || e.keyCode == KeyCode.End || e.keyCode == KeyCode.Home) { if (e.keyCode == KeyCode.End) { IndexEditItem = MidiPlayerGlobal.CurrentMidiSet.MidiFiles.Count - 1; } if (e.keyCode == KeyCode.Home) { IndexEditItem = 0; } if (e.keyCode == KeyCode.DownArrow) { IndexEditItem++; if (IndexEditItem >= MidiPlayerGlobal.CurrentMidiSet.MidiFiles.Count) { IndexEditItem = 0; } } if (e.keyCode == KeyCode.UpArrow) { IndexEditItem--; if (IndexEditItem < 0) { IndexEditItem = MidiPlayerGlobal.CurrentMidiSet.MidiFiles.Count - 1; } } SetMidiSelectedVisible(); ReadEvents(); GUI.changed = true; Repaint(); } } if (columnSF == null) { columnSF = new ToolsEditor.DefineColumn[2]; columnSF[0].Width = 60; columnSF[0].Caption = "Index"; columnSF[0].PositionCaption = 10f; columnSF[1].Width = 300; columnSF[1].Caption = "Midi Name"; columnSF[1].PositionCaption = 5f; //columnSF[2].Width = 70; columnSF[2].Caption = "Read"; columnSF[2].PositionCaption = 0f; //columnSF[3].Width = 60; columnSF[3].Caption = "Remove"; columnSF[3].PositionCaption = -9f; } GUI.Box(new Rect(startX, startY, width, height), "", stylePanel); float localstartX = 0; float localstartY = 0; GUIContent content = new GUIContent() { text = MidiPlayerGlobal.CurrentMidiSet.MidiFiles == null || MidiPlayerGlobal.CurrentMidiSet.MidiFiles.Count == 0 ? "No Midi file available" : "Midi files available", tooltip = "" }; localstartX += xpostitlebox; localstartY += ypostitlebox; GUI.Label(new Rect(startX + localstartX + 5, startY + localstartY, 160, titleHeight), content, styleBold); string searchMidi = EditorGUI.TextField(new Rect(startX + localstartX + 5 + 170 + espace, startY + localstartY - 2, 225, titleHeight), "Search in list:"); if (!string.IsNullOrEmpty(searchMidi)) { int index = MidiPlayerGlobal.CurrentMidiSet.MidiFiles.FindIndex(s => s.ToLower().Contains(searchMidi.ToLower())); if (index >= 0) { IndexEditItem = index; SetMidiSelectedVisible(); ReadEvents(); } } localstartY += titleHeight; if (GUI.Button(new Rect(startX + localstartX + width - 65, startY + localstartY - 18, 35, 35), buttonIconHelp)) { Application.OpenURL("https://paxstellar.fr/setup-mptk-add-midi-files-v2/"); } if (GUI.Button(new Rect(startX + localstartX + espace, startY + localstartY, buttonLargeWidth, buttonHeight), "Add a Midi File")) { AddMidifile(); } if (GUI.Button(new Rect(startX + localstartX + 2 * espace + buttonLargeWidth, startY + localstartY, buttonLargeWidth, buttonHeight), "Add All Midi from a Folder")) { AddMidiFromFolder(); } if (IndexEditItem >= 0 && IndexEditItem < MidiPlayerGlobal.CurrentMidiSet.MidiFiles.Count) { if (GUI.Button(new Rect(startX + localstartX + 7 * espace + 2 * buttonLargeWidth, startY + localstartY, 30, buttonHeight), new GUIContent(buttonIconDelete, $"Remove {MidiPlayerGlobal.CurrentMidiSet.MidiFiles[IndexEditItem]}"))) { if (EditorUtility.DisplayDialog( "Remove Midi File", $"Remove {MidiPlayerGlobal.CurrentMidiSet.MidiFiles[IndexEditItem]}", "ok", "cancel")) { DeleteResource(MidiLoad.BuildOSPath(MidiPlayerGlobal.CurrentMidiSet.MidiFiles[IndexEditItem])); AssetDatabase.Refresh(); ToolsEditor.LoadMidiSet(); ToolsEditor.CheckMidiSet(); AssetDatabase.Refresh(); } } } localstartY += buttonHeight + espace; // Draw title list box GUI.Box(new Rect(startX + localstartX + espace, startY + localstartY, width - 35, itemHeight), "", styleListTitle); float boxX = startX + localstartX + espace; foreach (ToolsEditor.DefineColumn column in columnSF) { GUI.Label(new Rect(boxX + column.PositionCaption, startY + localstartY, column.Width, itemHeight), column.Caption, styleLabelLeft); boxX += column.Width; } localstartY += itemHeight + espace; if (MidiPlayerGlobal.CurrentMidiSet.MidiFiles != null) { listMidiVisibleRect = new Rect(startX + localstartX, startY + localstartY - 6, width - 10, height - localstartY); Rect listMidiContentRect = new Rect(0, 0, width - 25, MidiPlayerGlobal.CurrentMidiSet.MidiFiles.Count * itemHeight + 5); scrollPosMidiFile = GUI.BeginScrollView(listMidiVisibleRect, scrollPosMidiFile, listMidiContentRect, false, true); //Debug.Log($"scrollPosMidiFile:{scrollPosMidiFile.y} listVisibleRect:{listMidiVisibleRect.height} listContentRect:{listMidiContentRect.height}"); float boxY = 0; // Loop on each midi // ----------------- for (int i = 0; i < MidiPlayerGlobal.CurrentMidiSet.MidiFiles.Count; i++) { boxX = 5; if (GUI.Button(new Rect(espace, boxY, width - 35, itemHeight), "", IndexEditItem == i ? styleListRowSelected : styleListRow)) { IndexEditItem = i; ReadEvents(); } // col 0 - Index float colw = columnSF[0].Width; EditorGUI.LabelField(new Rect(boxX + 1, boxY + 2, colw, itemHeight - 5), i.ToString(), styleLabelCenter); boxX += colw; // col 1 - Name colw = columnSF[1].Width; content = new GUIContent() { text = MidiPlayerGlobal.CurrentMidiSet.MidiFiles[i], tooltip = MidiPlayerGlobal.CurrentMidiSet.MidiFiles[i] }; EditorGUI.LabelField(new Rect(boxX + 5, boxY + 2, colw, itemHeight - 5), content, styleLabelLeft); boxX += colw; // col 2 - Select //colw = columnSF[2].Width; //if (GUI.Button(new Rect(boxX, boxY + 3, 30, buttonHeight), new GUIContent(buttonIconView, "Read Midi events"))) //{ // IndexEditItem = i; // ReadEvents(); //} //boxX += colw; // col 3 - remove //colw = columnSF[3].Width; //if (GUI.Button(new Rect(boxX, boxY + 3, 30, buttonHeight), new GUIContent(buttonIconDelete, "Remove Midi File"))) //{ // DeleteResource(MidiLoad.BuildOSPath(MidiPlayerGlobal.CurrentMidiSet.MidiFiles[i])); // AssetDatabase.Refresh(); // ToolsEditor.LoadMidiSet(); // ToolsEditor.CheckMidiSet(); // AssetDatabase.Refresh(); //} //boxX += colw; boxY += itemHeight - 1; } GUI.EndScrollView(); } } catch (Exception ex) { MidiPlayerGlobal.ErrorDetail(ex); } }