예제 #1
0
 static public void SfOptim(List <PatchOptim> filters)
 {
     try
     {
         if (MidiPlayerGlobal.ImSFCurrent != null)
         {
             for (int b = 0; b < MidiPlayerGlobal.ImSFCurrent.Banks.Length; b++)
             {
                 ImBank bank = MidiPlayerGlobal.ImSFCurrent.Banks[b];
                 if (bank != null)
                 {
                     for (int p = 0; p < bank.Presets.Length; p++)
                     {
                         ImPreset preset = bank.Presets[p];
                         if (preset != null)
                         {
                             bool found = false;
                             foreach (PatchOptim optim in filters)
                             {
                                 if (b == optim.Bank && p == optim.Patch && optim.Selected)
                                 {
                                     found = true;
                                     break;
                                 }
                             }
                             if (!found)
                             {
                                 bank.Presets[p] = null;
                             }
                         }
                     }
                 }
             }
         }
     }
     catch (System.Exception ex)
     {
         MidiPlayerGlobal.ErrorDetail(ex);
     }
 }
예제 #2
0
        /// <summary>
        /// Read the list of midi events available in the Midi from a ticks position to an end position.
        /// </summary>
        /// <param name="fromTicks">ticks start</param>
        /// <param name="toTicks">ticks end</param>
        /// <returns></returns>
        public List <MPTKEvent> MPTK_ReadMidiEvents(long fromTicks = 0, long toTicks = long.MaxValue)
        {
            List <MPTKEvent> midievents = new List <MPTKEvent>();

            try
            {
                if (midifile != null)
                {
                    foreach (TrackMidiEvent trackEvent in MidiSorted)
                    {
                        if (Quantization != 0)
                        {
                            trackEvent.AbsoluteQuantize = ((trackEvent.Event.AbsoluteTime + Quantization / 2) / Quantization) * Quantization;
                        }
                        else
                        {
                            trackEvent.AbsoluteQuantize = trackEvent.Event.AbsoluteTime;
                        }

                        //Debug.Log("ReadMidiEvents - timeFromStartMS:" + Convert.ToInt32(timeFromStartMS) + " LastTimeFromStartMS:" + Convert.ToInt32(LastTimeFromStartMS) + " CurrentPulse:" + CurrentPulse + " AbsoluteQuantize:" + trackEvent.AbsoluteQuantize);

                        if (trackEvent.AbsoluteQuantize >= fromTicks && trackEvent.AbsoluteQuantize <= toTicks)
                        {
                            ConvertToEvent(midievents, trackEvent);
                        }
                        if (trackEvent.AbsoluteQuantize > toTicks)
                        {
                            break;
                        }
                        //MPTK_TickCurrent = trackEvent.AbsoluteQuantize;
                        //MPTK_TickLast = trackEvent.AbsoluteQuantize;
                    }
                }
            }
            catch (System.Exception ex)
            {
                MidiPlayerGlobal.ErrorDetail(ex);
            }
            return(midievents);
        }
예제 #3
0
        /// <summary>
        /// Play the midi file defined in MPTK_MidiName
        /// </summary>
        public virtual void MPTK_Play()
        {
            try
            {
                if (MidiPlayerGlobal.SoundFontLoaded)
                {
                    playPause = false;
                    if (!midiIsPlaying)
                    {
                        // Load description of available soundfont
                        if (MidiPlayerGlobal.ImSFCurrent != null && MidiPlayerGlobal.CurrentMidiSet != null && MidiPlayerGlobal.CurrentMidiSet.MidiFiles != null && MidiPlayerGlobal.CurrentMidiSet.MidiFiles.Count > 0)
                        {
                            //Debug.Log(MPTK_MidiName);
                            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];
                            }

                            StartCoroutine(ThreadPlay());
                            //StartCoroutine(TestWithDelay());
                        }
                        else
                        {
                            Debug.LogWarning("MidiFilePlayer - no SoundFont or Midi set defined, go to Unity menu Tools to setup MPTK");
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
                MidiPlayerGlobal.ErrorDetail(ex);
            }
        }
예제 #4
0
 /// <summary>
 /// Return sample to play according preset, key and velocity
 /// </summary>
 /// <param name="idxbank"></param>
 /// <param name="idxpreset"></param>
 /// <param name="key"></param>
 /// <param name="vel"></param>
 /// <returns></returns>
 public static ImSample GetImSample(int idxbank, int idxpreset, int key, int vel)
 {
     try
     {
         if (ImSFCurrent.Banks[idxbank] != null)
         {
             ImPreset preset = ImSFCurrent.Banks[idxbank].Presets[idxpreset];
             if (preset != null && preset.Instruments != null)
             {
                 foreach (ImInstrument instrument in preset.Instruments)
                 {
                     if (!instrument.HasKey || (key >= instrument.KeyStart && key <= instrument.KeyEnd))
                     {
                         if (!instrument.HasVel || (vel >= instrument.VelStart && vel <= instrument.VelEnd))
                         {
                             foreach (ImSample sample in instrument.Samples)
                             {
                                 if (sample.WaveFile != null)
                                 {
                                     if (!sample.HasKey || (key >= sample.KeyStart && key <= sample.KeyEnd))
                                     {
                                         if (!sample.HasVel || (vel >= sample.VelStart && vel <= sample.VelEnd))
                                         {
                                             return(sample);
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     catch (System.Exception ex)
     {
         MidiPlayerGlobal.ErrorDetail(ex);
     }
     return(null);
 }
예제 #5
0
        private void AnalyseMidi()
        {
            try
            {
                MPTK_TickLast       = 0;
                MPTK_TickCurrent    = 0;
                SequenceTrackName   = "";
                ProgramName         = "";
                TrackInstrumentName = "";
                TextEvent           = "";
                Copyright           = "";

                // Get midi info sorted from midifile.Events
                MPTK_MidiEvents = GetMidiEvents();

                //DebugMidiSorted(MidiSorted);
                MPTK_DeltaTicksPerQuarterNote = midifile.DeltaTicksPerQuarterNote;

                if (MPTK_InitialTempo < 0)
                {
                    MPTK_InitialTempo = 120;
                    miditempo         = (int)(MPTK_InitialTempo * 60000000d);
                }

                // Set initial tempo and duration
                fluid_player_set_bpm((int)MPTK_InitialTempo);

                if (!EnableChangeTempo)
                {
                    // Calculate the real duration from the PulseLength set with MPTK_InitialTempo
                    MPTK_DurationMS = MPTK_TickLast * (float)MPTK_PulseLenght;
                }
                MPTK_Duration = TimeSpan.FromMilliseconds(MPTK_DurationMS);
                //Debug.Log("MPTK_InitialTempo:" + MPTK_InitialTempo);
            }
            catch (System.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))
         {
             // selectedFile contins also the folder
             ToolsEditor.lastDirectoryMidi = Path.GetDirectoryName(selectedFile);
             InsertMidiFIle(selectedFile);
         }
         AssetDatabase.Refresh();
         ToolsEditor.LoadMidiSet();
         ToolsEditor.CheckMidiSet();
         AssetDatabase.Refresh();
         ReadEvents();
     }
     catch (System.Exception ex)
     {
         MidiPlayerGlobal.ErrorDetail(ex);
     }
 }
예제 #7
0
        //static private GUIStyle styleInfoMidi;

        // PopupSelectMidi PopMidi;


        void OnEnable()
        {
            try
            {
                //Debug.Log("OnEnable MidiFilePlayerEditor");
                CustomEventStartPlayMidi  = serializedObject.FindProperty("OnEventStartPlayMidi");
                CustomEventListNotesEvent = serializedObject.FindProperty("OnEventNotesMidi");
                CustomEventEndPlayMidi    = serializedObject.FindProperty("OnEventEndPlayMidi");

                instance = (MidiFilePlayer)target;
                // Load description of available soundfont
                if (MidiPlayerGlobal.CurrentMidiSet == null || MidiPlayerGlobal.CurrentMidiSet.ActiveSounFontInfo == null)
                {
                    ToolsEditor.LoadMidiSet();
                    ToolsEditor.CheckMidiSet();
                }
            }
            catch (System.Exception ex)
            {
                MidiPlayerGlobal.ErrorDetail(ex);
            }
        }
예제 #8
0
        /// <summary>
        /// LOad setting (run mode)
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static MidiSet LoadRsc(string data)
        {
            MidiSet loaded = null;

            try
            {
                if (!string.IsNullOrEmpty(data))
                {
                    var serializer = new XmlSerializer(typeof(MidiSet));
                    using (TextReader reader = new StringReader(data))
                    {
                        loaded = serializer.Deserialize(reader) as MidiSet;
                    }
                }
            }
            catch (System.Exception ex)
            {
                MidiPlayerGlobal.ErrorDetail(ex);
            }

            return(loaded);
        }
예제 #9
0
        /// <summary>
        /// Load samples associated to a patch for High SF
        /// </summary>
        private static void LoadAudioClip()
        {
            try
            {
                float start = Time.realtimeSinceStartup;
                //Debug.Log(">>> Load Sample");
                //int count = 0;
                if (ImSFCurrent != null)
                {
                    foreach (HiSample smpl in ImSFCurrent.HiSf.Samples)
                    {
                        if (smpl.Name != null)
                        {
                            if (!DicAudioClip.Exist(smpl.Name))
                            {
                                string    path = WavePath + "/" + Path.GetFileNameWithoutExtension(smpl.Name);// + ".wav";
                                AudioClip ac   = Resources.Load <AudioClip>(path);
                                if (ac != null)
                                {
                                    //Debug.Log("Sample load " + path);
                                    DicAudioClip.Add(smpl.Name, ac);

                                    MPTK_CountWaveLoaded++;
                                }
                                //else Debug.LogWarning("Sample " + smpl.WaveFile + " not found");
                            }
                        }
                    }
                }
                else
                {
                    Debug.Log("SoundFont not loaded ");
                }
            }
            catch (System.Exception ex)
            {
                MidiPlayerGlobal.ErrorDetail(ex);
            }
        }
예제 #10
0
        /// <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" });
                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);
                    }

                    string filenameToSave = Path.Combine(pathMidiFile, Path.GetFileNameWithoutExtension(selectedFile) + MidiPlayerGlobal.ExtensionMidiFile);
                    // Create a copy of the midi file in resources
                    File.Copy(selectedFile, filenameToSave, true);

                    if (MidiPlayerGlobal.CurrentMidiSet.MidiFiles == null)
                    {
                        MidiPlayerGlobal.CurrentMidiSet.MidiFiles = new List <string>();
                    }
                    string midiname = Path.GetFileNameWithoutExtension(selectedFile);
                    if (MidiPlayerGlobal.CurrentMidiSet.MidiFiles.FindIndex(s => s == midiname) < 0)
                    {
                        MidiPlayerGlobal.CurrentMidiSet.MidiFiles.Add(midiname);
                        MidiPlayerGlobal.CurrentMidiSet.Save();
                    }
                }
                AssetDatabase.Refresh();
            }
            catch (System.Exception ex)
            {
                MidiPlayerGlobal.ErrorDetail(ex);
            }
        }
예제 #11
0
        public static void Init()
        {
            // Get existing open window or if none, make a new one:
            try
            {
                window = (SoundFontSetupWindow)EditorWindow.GetWindow(typeof(SoundFontSetupWindow));
                window.titleContent.text = "SoundFont Setup";
                window.minSize           = new Vector2(828 + 65, 565);

                styleBold           = new GUIStyle(EditorStyles.boldLabel);
                styleBold.fontStyle = FontStyle.Bold;


                styleRed = new GUIStyle(EditorStyles.label);
                styleRed.normal.textColor = new Color(0.5f, 0, 0);
                styleRed.fontStyle        = FontStyle.Bold;

                styleRichText           = new GUIStyle(EditorStyles.label);
                styleRichText.richText  = true;
                styleRichText.alignment = TextAnchor.UpperLeft;
                heightLine = styleRichText.lineHeight * 1.2f;

                espace       = 5;
                widthLeft    = 415 + 25;
                heightTop    = 130;
                heightMiddle = 150;
                itemHeight   = 25;
                buttonWidth  = 200;
                buttonHeight = 18;

                xpostitlebox = 2;
                ypostitlebox = 5;
            }
            catch (System.Exception ex)
            {
                MidiPlayerGlobal.ErrorDetail(ex);
            }
        }
예제 #12
0
        /// <summary>
        /// Load Midi from midi MPTK referential (Unity resource).
        /// The index of the Midi file can be found in the windo "Midi File Setup". Display with menu MPTK / Midi File Setup
        ///! @code
        /// public MidiLoad MidiLoaded;
        /// // .....
        /// MidiLoaded = new MidiLoad();
        /// MidiLoaded.MPTK_Load(14) // index for "Beattles - Michelle"
        /// Debug.Log("Duration:" + MidiLoaded.MPTK_Duration);
        ///! @endcode
        /// </summary>
        /// <param name="index"></param>
        /// <param name="strict">If true will error on non-paired note events, default:false</param>
        /// <returns>true if loaded</returns>
        public bool MPTK_Load(int index, bool strict = false)
        {
            Init();
            bool ok = true;

            try
            {
                if (MidiPlayerGlobal.CurrentMidiSet.MidiFiles != null && MidiPlayerGlobal.CurrentMidiSet.MidiFiles.Count > 0)
                {
                    if (index >= 0 && index < MidiPlayerGlobal.CurrentMidiSet.MidiFiles.Count)
                    {
                        string    midiname = MidiPlayerGlobal.CurrentMidiSet.MidiFiles[index];
                        TextAsset mididata = Resources.Load <TextAsset>(Path.Combine(MidiPlayerGlobal.MidiFilesDB, midiname));
                        midifile = new MidiFile(mididata.bytes, strict);
                        if (midifile != null)
                        {
                            AnalyseMidi();
                        }
                    }
                    else
                    {
                        Debug.LogWarningFormat("MidiLoad - index {0} out of range ", index);
                        ok = false;
                    }
                }
                else
                {
                    Debug.LogWarningFormat("MidiLoad - index:{0} - {1}", index, MidiPlayerGlobal.ErrorNoMidiFile);
                    ok = false;
                }
            }
            catch (System.Exception ex)
            {
                MidiPlayerGlobal.ErrorDetail(ex);
                ok = false;
            }
            return(ok);
        }
예제 #13
0
        public static void ErrorNoMidiFile()
        {
            GUIStyle labError = new GUIStyle("Label");

            labError.normal.background = SetColor(new Texture2D(2, 2), new Color(0.9f, 0.9f, 0.9f));
            labError.normal.textColor  = new Color(0.8f, 0.1f, 0.1f);
            labError.alignment         = TextAnchor.MiddleLeft;
            labError.wordWrap          = true;
            labError.fontSize          = 12;
            Texture buttonIconFolder = Resources.Load <Texture2D>("Textures/question-mark");

            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.LabelField(MidiPlayerGlobal.ErrorNoMidiFile, labError, GUILayout.Height(40f));
            if (GUILayout.Button(new GUIContent(buttonIconFolder, "Help"), GUILayout.Width(40f), GUILayout.Height(40f)))
            {
                Application.OpenURL("https://paxstellar.fr/setup-mptk-quick-start-v2/");
            }
            EditorGUILayout.EndHorizontal();
            MidiPlayerGlobal.InitPath();
            ToolsEditor.LoadMidiSet();
            ToolsEditor.CheckMidiSet();
            Debug.Log(MidiPlayerGlobal.ErrorNoMidiFile);
        }
예제 #14
0
        /// <summary>
        /// Calculate PulseLenghtMS from QuarterPerMinute value
        /// </summary>
        /// <param name="tempo"></param>
        public void ChangeTempo(double tempo)
        {
            try
            {
                QuarterPerMinuteValue = tempo;
                TickLengthMs          = (1000d / ((QuarterPerMinuteValue * midifile.DeltaTicksPerQuarterNote) / 60f)) / Speed;
                //The BPM measures how many quarter notes happen in a minute. To work out the length of each pulse we can use the following formula: Pulse Length = 60 / (BPM * PPQN)
                //16  Sixteen Double croche

                // Update total time of midi play
                CalculateDuration();

                if (LogEvents)
                {
                    Debug.Log(string.Format("ChangeTempo QuarterPerMinuteValue:{0:0.00} Speed:{1:0.00} DeltaTicksPerQuarterNote:{2:0.00} PulseLength:{3:0.00} ms  Duration:{4:0.00} s",
                                            QuarterPerMinuteValue, Speed, midifile.DeltaTicksPerQuarterNote, TickLengthMs, MPTK_Duration.TotalSeconds));
                }
            }
            catch (System.Exception ex)
            {
                MidiPlayerGlobal.ErrorDetail(ex);
            }
        }
예제 #15
0
파일: ImBank.cs 프로젝트: Bimane1900/Rhythm
        public List <string> GetDescription()
        {
            List <string> description = new List <string>();

            try
            {
                if (defpresets != null)
                {
                    foreach (HiPreset preset in defpresets)
                    {
                        if (preset != null)
                        {
                            description.Add(string.Format("[{0:000}] {1}", preset.Num, preset.Name));
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
                MidiPlayerGlobal.ErrorDetail(ex);
            }
            return(description);
        }
예제 #16
0
 public void Add(string line, int mode = 0)
 {
     try
     {
         //Debug.Log(line);
         if (mode == 0)
         {
             info1.Add(line);
         }
         else if (mode == 1)
         {
             info2.Add(line);
         }
         else if (mode == 2)
         {
             info3.Add(line);
         }
     }
     catch (System.Exception ex)
     {
         MidiPlayerGlobal.ErrorDetail(ex);
     }
 }
예제 #17
0
 static public string LabelFromEcart(int ecart)
 {
     try
     {
         if (ListEcart == null)
         {
             Init();
         }
         if (ecart < 0 || ecart >= 12)
         {
             return("xx");
         }
         else
         {
             return(ListEcart[ecart].Label);
         }
     }
     catch (System.Exception ex)
     {
         MidiPlayerGlobal.ErrorDetail(ex);
     }
     return("xx");
 }
예제 #18
0
 static public string LabelFromMidi(int midi)
 {
     try
     {
         if (ListNote == null)
         {
             Init();
         }
         if (midi < 0 || midi >= ListNote.Count)
         {
             return("xx");
         }
         else
         {
             return(ListNote[midi].Label);
         }
     }
     catch (System.Exception ex)
     {
         MidiPlayerGlobal.ErrorDetail(ex);
     }
     return("xx");
 }
예제 #19
0
        //static public float RatioFromHauteur(int hauteur)
        //{
        //    int index = hauteur + 39;
        //    if (index < 0 || index >= ListNote.Count)
        //        return 1f;
        //    else
        //        return ListNote[index].Ratio;
        //}

        static public bool IsSharp(int midi)
        {
            try
            {
                if (ListNote == null)
                {
                    Init();
                }
                if (midi < 0 || midi >= ListNote.Count)
                {
                    return(false);
                }
                else
                {
                    return(ListNote[midi].Sharp);
                }
            }
            catch (System.Exception ex)
            {
                MidiPlayerGlobal.ErrorDetail(ex);
            }
            return(false);
        }
예제 #20
0
        private IEnumerator TheadPlay(List <MPTKNote> notes)
        {
            if (notes != null && notes.Count > 0)
            {
                try
                {
                    if (MPTK_PauseOnDistance)
                    {
                        distanceEditorModeOnly = MidiPlayerGlobal.MPTK_DistanceToListener(this.transform);
                        if (distanceEditorModeOnly > AudioSourceTemplate.maxDistance)
                        {
                            notes.Clear();
                        }
                    }
                }
                catch (System.Exception ex)
                {
                    MidiPlayerGlobal.ErrorDetail(ex);
                }

                try
                {
                    List <MidiNote> midinotes = new List <MidiNote>();
                    foreach (MPTKNote note in notes)
                    {
                        midinotes.Add(note.ToMidiNote());
                    }
                    MPTK_PlayNotes(midinotes);
                    //Debug.Log("---------------- play count:" + notes.Count + " " + timeFromStartMS );
                }
                catch (System.Exception ex)
                {
                    MidiPlayerGlobal.ErrorDetail(ex);
                }
            }
            yield return(0);
        }
예제 #21
0
        private void BankPatchChanged(object tag, int index)
        {
            switch ((string)tag)
            {
            case "BANK_INST":
                MidiPlayerGlobal.MPTK_SelectBankInstrument(index);
                midiStreamPlayer.MPTK_PlayEvent(new MPTKEvent()
                {
                    Command = MPTKCommand.ControlChange, Controller = MPTKController.BankSelect, Value = index, Channel = StreamChannel,
                });
                break;

            case "PATCH_INST":
                CurrentPatchInstrument = index;
                midiStreamPlayer.MPTK_PlayEvent(new MPTKEvent()
                {
                    Command = MPTKCommand.PatchChange, Value = index, Channel = StreamChannel,
                });
                break;

            case "BANK_DRUM":
                MidiPlayerGlobal.MPTK_SelectBankDrum(index);
                midiStreamPlayer.MPTK_PlayEvent(new MPTKEvent()
                {
                    Command = MPTKCommand.ControlChange, Controller = MPTKController.BankSelect, Value = index, Channel = 9,
                });
                break;

            case "PATCH_DRUM":
                CurrentPatchDrum = index;
                midiStreamPlayer.MPTK_PlayEvent(new MPTKEvent()
                {
                    Command = MPTKCommand.PatchChange, Value = index, Channel = 9
                });
                break;
            }
        }
예제 #22
0
        void OnEnable()
        {
            try
            {
                instance = (MidiFilePlayer)target;
                //Debug.Log("MidiFilePlayerEditor OnEnable " + instance.MPTK_MidiIndex);
                //Debug.Log("OnEnable MidiFilePlayerEditor");
                CustomEventStartPlayMidi  = serializedObject.FindProperty("OnEventStartPlayMidi");
                CustomEventListNotesEvent = serializedObject.FindProperty("OnEventNotesMidi");
                CustomEventEndPlayMidi    = serializedObject.FindProperty("OnEventEndPlayMidi");

                if (!Application.isPlaying)
                {
                    // Load description of available soundfont
                    if (MidiPlayerGlobal.CurrentMidiSet == null || MidiPlayerGlobal.CurrentMidiSet.ActiveSounFontInfo == null)
                    {
                        MidiPlayerGlobal.InitPath();
                        ToolsEditor.LoadMidiSet();
                        ToolsEditor.CheckMidiSet();
                    }
                }

                if (winSelectMidi != null)
                {
                    //Debug.Log("OnEnable winSelectMidi " + winSelectMidi.Title);
                    winSelectMidi.SelectedItem = instance.MPTK_MidiIndex;
                    winSelectMidi.Repaint();
                    winSelectMidi.Focus();
                }

                //EditorApplication.playModeStateChanged += EditorApplication_playModeStateChanged;
            }
            catch (System.Exception ex)
            {
                MidiPlayerGlobal.ErrorDetail(ex);
            }
        }
예제 #23
0
        /// <summary>
        /// Load Midi from midi MPTK referential (Unity resource).
        /// The index of the Midi file can be found in the windo "Midi File Setup". Display with menu MPTK / Midi File Setup
        /// </summary>
        /// <param name="index"></param>
        public bool MPTK_Load(int index)
        {
            //! @code
            //! public MidiLoad MidiLoaded;
            //! // .....
            //! MidiLoaded = new MidiLoad();
            //! MidiLoaded.MPTK_Load(14) // index for "Beattles - Michelle"
            //! Debug.Log("Duration:" + MidiLoaded.MPTK_Duration);
            //! @endcode
            Init();
            bool ok = true;

            try
            {
                if (index >= 0 && index < MidiPlayerGlobal.CurrentMidiSet.MidiFiles.Count)
                {
                    string    midiname = MidiPlayerGlobal.CurrentMidiSet.MidiFiles[index];
                    TextAsset mididata = Resources.Load <TextAsset>(Path.Combine(MidiPlayerGlobal.MidiFilesDB, midiname));
                    midifile = new MidiFile(mididata.bytes, false);
                    if (midifile != null)
                    {
                        AnalyseMidi();
                    }
                }
                else
                {
                    Debug.LogWarning("MidiLoad - index out of range " + index);
                    ok = false;
                }
            }
            catch (System.Exception ex)
            {
                MidiPlayerGlobal.ErrorDetail(ex);
                ok = false;
            }
            return(ok);
        }
예제 #24
0
        public static void Init()
        {
            //Debug.Log("init");
            // Get existing open window or if none, make a new one:
            try
            {
                window         = GetWindow <SoundFontSetupWindow>(true, "SoundFont Setup");
                window.minSize = new Vector2(828 + 65, 565);

                styleBold           = new GUIStyle(EditorStyles.boldLabel);
                styleBold.fontStyle = FontStyle.Bold;

                styleMiniButton             = new GUIStyle(EditorStyles.miniButtonMid);
                styleMiniButton.fixedWidth  = 16;
                styleMiniButton.fixedHeight = 16;

                styleListTitle = new GUIStyle("box");

                styleRed = new GUIStyle(EditorStyles.label);
                styleRed.normal.textColor = new Color(0.5f, 0, 0);
                styleRed.fontStyle        = FontStyle.Bold;

                styleRichText           = new GUIStyle(EditorStyles.label);
                styleRichText.richText  = true;
                styleRichText.alignment = TextAnchor.UpperLeft;

                styleLabelRight           = new GUIStyle(EditorStyles.label);
                styleLabelRight.alignment = TextAnchor.MiddleRight;
                //styleLabelRight.normal.background = ToolsEditor.SetColor(new Texture2D(2, 2), new Color(.6f, .8f, .6f, 1f));
            }
            catch (System.Exception ex)
            {
                MidiPlayerGlobal.ErrorDetail(ex);
            }
            //Debug.Log("end init");
        }
예제 #25
0
        /// <summary>
        /// Load an ImSoundFont from a desktop file
        /// </summary>
        /// <param name="path"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public static ImSoundFont Load(string path, string name)
        {
            ImSoundFont loaded = null;

            try
            {
                string Filepath = Path.Combine(path, name);
                Filepath += MidiPlayerGlobal.ExtensionSoundFileFile;

                if (File.Exists(Filepath))
                {
                    var serializer = new XmlSerializer(typeof(ImSoundFont));
                    using (var stream = new FileStream(Filepath, FileMode.Open))
                    {
                        loaded = serializer.Deserialize(stream) as ImSoundFont;
                    }
                }
            }
            catch (System.Exception ex)
            {
                MidiPlayerGlobal.ErrorDetail(ex);
            }
            return(loaded);
        }
예제 #26
0
 private static void RenameExtFileFromMidToBytes()
 {
     try
     {
         string folder = Application.dataPath + "/" + MidiPlayerGlobal.PathToMidiFile;
         if (Directory.Exists(folder))
         {
             string[] fileEntries = Directory.GetFiles(folder, "*.mid", SearchOption.AllDirectories);
             foreach (string filename in fileEntries)
             {
                 try
                 {
                     string target = Path.ChangeExtension(filename, MidiPlayerGlobal.ExtensionMidiFile);
                     if (File.Exists(target))
                     {
                         File.Delete(target);
                     }
                     File.Move(filename, target);
                     string meta = Path.ChangeExtension(filename, ".meta");
                     if (File.Exists(meta))
                     {
                         File.Delete(meta);
                     }
                 }
                 catch (System.Exception ex)
                 {
                     MidiPlayerGlobal.ErrorDetail(ex);
                 }
             }
         }
     }
     catch (System.Exception ex)
     {
         MidiPlayerGlobal.ErrorDetail(ex);
     }
 }
예제 #27
0
        /// <summary>
        /// Load Midi from an array of bytes
        /// </summary>
        /// <param name="datamidi">byte arry midi</param>
        /// <param name="strict">If true will error on non-paired note events, default:false</param>
        /// <returns>true if loaded</returns>
        public bool MPTK_Load(byte[] datamidi, bool strict = false)
        {
            Init();
            bool ok = true;

            try
            {
                midifile = new MidiFile(datamidi, strict);
                if (midifile != null)
                {
                    AnalyseMidi();
                }
                else
                {
                    ok = false;
                }
            }
            catch (System.Exception ex)
            {
                MidiPlayerGlobal.ErrorDetail(ex);
                ok = false;
            }
            return(ok);
        }
예제 #28
0
        private IEnumerator <float> TheadPlay(MPTKEvent evnt)
        {
            if (evnt != null)
            {
                try
                {
                    //TBR if (!MPTK_PauseOnDistance || MidiPlayerGlobal.MPTK_DistanceToListener(this.transform) <= VoiceTemplate.Audiosource.maxDistance)
                    {
#if DEBUGPERF
                        DebugPerf("-----> Init perf:", 0);
#endif
                        PlayEvent(evnt);
#if DEBUGPERF
                        DebugPerf("<---- ClosePerf perf:", 2);
#endif
                    }
                }
                catch (System.Exception ex)
                {
                    MidiPlayerGlobal.ErrorDetail(ex);
                }
            }
            yield return(0);
        }
예제 #29
0
        void OnGUI()
        {
            try
            {
                //Debug.Log("ongui");
                KeepOpen = true;
                list     = new List <MPTKListItem>();
                foreach (string midiname in MidiPlayerGlobal.CurrentMidiSet.MidiFiles)
                {
                    list.Add(new MPTKListItem()
                    {
                        Label = midiname, Index = list.Count
                    });
                }
                ColWidth           = 250;
                ColHeight          = 30;
                calculatedColCount = 3;
                EspaceX            = 5;
                EspaceY            = 5;
                TitleHeight        = 30;
                countRow           = (int)((float)list.Count / (float)calculatedColCount + 1f);
                resizedWidth       = (int)SelectWindow.position.size.x;;
                resizedHeight      = (int)SelectWindow.position.size.y;

                if (myStyle == null)
                {
                    myStyle = new CustomStyle();
                }

                DrawWindow();
            }
            catch (Exception ex)
            {
                MidiPlayerGlobal.ErrorDetail(ex);
            }
        }
        /// <summary>
        /// Reload data
        /// </summary>
        private void OnFocus()
        {
            // Load description of available soundfont
            try
            {
                Init();

                MidiPlayerGlobal.InitPath();

                //Debug.Log(MidiPlayerGlobal.ImSFCurrent == null ? "ImSFCurrent is null" : "ImSFCurrent:" + MidiPlayerGlobal.ImSFCurrent.SoundFontName);
                //Debug.Log(MidiPlayerGlobal.CurrentMidiSet == null ? "CurrentMidiSet is null" : "CurrentMidiSet" + MidiPlayerGlobal.CurrentMidiSet.ActiveSounFontInfo.Name);
                //Debug.Log(MidiPlayerGlobal.CurrentMidiSet.ActiveSounFontInfo == null ? "ActiveSounFontInfo is null" : MidiPlayerGlobal.CurrentMidiSet.ActiveSounFontInfo.Name);
                ToolsEditor.LoadMidiSet();
                ToolsEditor.CheckMidiSet();
                // cause catch if call when playing (setup open on run mode)
                try
                {
                    if (!Application.isPlaying)
                    {
                        AssetDatabase.Refresh();
                    }
                }
                catch (Exception)
                {
                }
                // Exec after Refresh, either cause errror
                if (MidiPlayerGlobal.ImSFCurrent == null)
                {
                    MidiPlayerGlobal.LoadCurrentSF();
                }
            }
            catch (Exception ex)
            {
                MidiPlayerGlobal.ErrorDetail(ex);
            }
        }