Ejemplo n.º 1
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);
            }
        }
Ejemplo n.º 2
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);
        }
        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);
            }
        }
Ejemplo n.º 4
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);
     }
 }
Ejemplo n.º 5
0
        private void SelectSong(float width, float height)
        {
            try
            {
                string   folder = Path.Combine(Application.dataPath, MidiPlayerGlobal.PathToSong);
                string[] fileEntries;
                if (Directory.Exists(folder))
                {
                    fileEntries = Directory.GetFiles(folder, "*.txt", SearchOption.AllDirectories);
                }
                else
                {
                    fileEntries = new string[0];
                }

                scrollListSong = GUILayout.BeginScrollView(scrollListSong, false, false, myStyle.HScroll, myStyle.VScroll, myStyle.BackgWindow, GUILayout.Width(200), GUILayout.Height(200));
                foreach (string s in fileEntries)
                {
                    string   songname = Path.GetFileNameWithoutExtension(s);
                    GUIStyle styleBt  = myStyle.BtStandard;
                    if (SelectedSongName == songname)
                    {
                        styleBt = myStyle.BtSelected;
                    }

                    if (GUILayout.Button(songname, styleBt))
                    {
                        SelectedSongName = Path.GetFileNameWithoutExtension(s);
                    }
                }
                GUILayout.EndScrollView();
            }
            catch (Exception ex)
            {
                MidiPlayerGlobal.ErrorDetail(ex);
            }
        }
Ejemplo n.º 6
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);
     }
 }
Ejemplo n.º 7
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);
        }
Ejemplo n.º 8
0
        public override void OnInspectorGUI()
        {
            try
            {
                //if (styleInfoMidi == null)
                //{
                //    styleInfoMidi = new GUIStyle(EditorStyles.textArea);
                //    styleInfoMidi.normal.textColor = new Color(0, 0, 0.99f);
                //    styleInfoMidi.alignment = TextAnchor.UpperLeft;
                //    //styleDragZone.border = new RectOffset(2, 2, 2, 2);
                //}



                GUI.changed = false;
                GUI.color   = Color.white;

                //Transform t = (Transform)target;
                //Debug.Log(t.localPosition+" " + t.position);

                //mDebug.Log(Event.current.type);
                Event e = Event.current;

                string soundFontSelected = "No SoundFont selected.";
                if (MidiPlayerGlobal.CurrentMidiSet != null && MidiPlayerGlobal.CurrentMidiSet.ActiveSounFontInfo != null)
                {
                    soundFontSelected = MidiPlayerGlobal.CurrentMidiSet.ActiveSounFontInfo.Name;
                    EditorGUILayout.LabelField(new GUIContent("SoundFont: " + soundFontSelected, "Define SoundFont from the menu 'Tools/MPTK - SoundFont Setup' or alt-f"));
                    EditorGUILayout.Separator();

                    EditorGUILayout.BeginHorizontal();
                    EditorGUILayout.LabelField(new GUIContent("Midi ", "Select Midi File to play"), GUILayout.Width(150));

                    //if (GUILayout.Button(new GUIContent("Refresh", "Reload all Midi from resource folder"))) MidiPlayerGlobal.CheckMidiSet();
                    if (MidiPlayerGlobal.CurrentMidiSet.MidiFiles != null && MidiPlayerGlobal.CurrentMidiSet.MidiFiles.Count > 0)
                    {
                        // Search index from midi name
                        int selectedMidi = instance.MPTK_MidiIndex;
                        if (selectedMidi < 0)
                        {
                            selectedMidi           = 0;
                            instance.MPTK_MidiName = MidiPlayerGlobal.CurrentMidiSet.MidiFiles[selectedMidi];
                        }
                        int newSelectMidi = EditorGUILayout.Popup(selectedMidi, MidiPlayerGlobal.CurrentMidiSet.MidiFiles.ToArray());
                        // Is midifile has changed ?
                        if (newSelectMidi != selectedMidi)
                        {
                            instance.MPTK_MidiIndex = newSelectMidi;
                            instance.MPTK_RePlay();
                        }
                    }
                    else
                    {
                        EditorGUILayout.LabelField("No Midi defined, go to menu 'Tools/MPTK - Midi File Setup' or alt-m");
                        instance.MPTK_MidiName = "";
                    }
                    EditorGUILayout.EndHorizontal();

                    float volume = EditorGUILayout.Slider(new GUIContent("Volume", "Set global volume for this midi playing"), instance.MPTK_Volume, 0f, 1f);
                    if (instance.MPTK_Volume != volume)
                    {
                        instance.MPTK_Volume = volume;
                    }


                    instance.MPTK_PlayOnStart        = EditorGUILayout.Toggle(new GUIContent("Play At Startup", "Start playing midi when the application starts"), instance.MPTK_PlayOnStart);
                    instance.MPTK_DirectSendToPlayer = EditorGUILayout.Toggle(new GUIContent("Direct send to player", "Midi events are send to the midi player directly"), instance.MPTK_DirectSendToPlayer);

                    EditorGUILayout.BeginHorizontal();
                    string tooltipDistance = "Playing is paused if distance between AudioListener and this component is greater than MaxDistance";
                    instance.MPTK_PauseOnDistance = EditorGUILayout.Toggle(new GUIContent("Pause With Distance", tooltipDistance), instance.MPTK_PauseOnDistance);
                    EditorGUILayout.LabelField(new GUIContent("Current:" + Math.Round(instance.distanceEditorModeOnly, 2), tooltipDistance));
                    EditorGUILayout.EndHorizontal();

                    float distance = EditorGUILayout.Slider(new GUIContent("Max Distance", tooltipDistance), instance.MPTK_MaxDistance, 0f, 500f);
                    if (instance.MPTK_MaxDistance != distance)
                    {
                        instance.MPTK_MaxDistance = distance;
                    }

                    instance.MPTK_Loop = EditorGUILayout.Toggle(new GUIContent("Loop", "Enable loop on midi play"), instance.MPTK_Loop);

                    EditorGUILayout.BeginHorizontal();
                    EditorGUILayout.PrefixLabel("Speed");
                    float speed = EditorGUILayout.Slider(instance.MPTK_Speed, 0.1f, 5f);
                    if (instance.MPTK_Speed != speed)
                    {
                        instance.MPTK_Speed = speed;
                    }
                    EditorGUILayout.EndHorizontal();


                    EditorGUILayout.BeginHorizontal();
                    EditorGUILayout.PrefixLabel("Transpose");
                    instance.MPTK_Transpose = EditorGUILayout.IntSlider(instance.MPTK_Transpose, -24, 24);
                    EditorGUILayout.EndHorizontal();

                    EditorGUILayout.BeginHorizontal();
                    EditorGUILayout.PrefixLabel("Release Time (sec.)");
                    instance.MPTK_TimeToRelease = EditorGUILayout.Slider(instance.MPTK_TimeToRelease, 0.05f, 1f);
                    EditorGUILayout.EndHorizontal();

                    instance.MPTK_LogWaves = EditorGUILayout.Toggle(new GUIContent("Log Waves", "Log information about wave for each notes played"), instance.MPTK_LogWaves);

                    if (EditorApplication.isPlaying)
                    {
                        EditorGUILayout.Separator();
                        EditorGUILayout.LabelField("Time", instance.playTimeEditorModeOnly + " / " + instance.durationEditorModeOnly);

                        EditorGUILayout.BeginHorizontal();
                        EditorGUILayout.PrefixLabel("Position");
                        float pos = EditorGUILayout.Slider(instance.MPTK_Position, 0f, (float)instance.MPTK_Duration.TotalMilliseconds);
                        if (instance.MPTK_Position != pos)
                        {
                            instance.MPTK_Position = pos;
                        }
                        EditorGUILayout.EndHorizontal();

                        EditorGUILayout.BeginHorizontal();

                        if (instance.MPTK_IsPlaying && !instance.MPTK_IsPaused)
                        {
                            GUI.color = ToolsEditor.ButtonColor;
                        }
                        if (GUILayout.Button(new GUIContent("Play", "")))
                        {
                            instance.MPTK_Play();
                        }
                        GUI.color = Color.white;

                        if (instance.MPTK_IsPaused)
                        {
                            GUI.color = ToolsEditor.ButtonColor;
                        }
                        if (GUILayout.Button(new GUIContent("Pause", "")))
                        {
                            if (instance.MPTK_IsPaused)
                            {
                                instance.MPTK_Play();
                            }
                            else
                            {
                                instance.MPTK_Pause();
                            }
                        }
                        GUI.color = Color.white;

                        if (GUILayout.Button(new GUIContent("Stop", "")))
                        {
                            instance.MPTK_Stop();
                        }

                        if (GUILayout.Button(new GUIContent("Restart", "")))
                        {
                            instance.MPTK_RePlay();
                        }
                        EditorGUILayout.EndHorizontal();

                        EditorGUILayout.BeginHorizontal();
                        if (GUILayout.Button(new GUIContent("Previous", "")))
                        {
                            instance.MPTK_Previous();
                        }
                        if (GUILayout.Button(new GUIContent("Next", "")))
                        {
                            instance.MPTK_Next();
                        }
                        EditorGUILayout.EndHorizontal();
                    }

                    showMidiParameter = EditorGUILayout.Foldout(showMidiParameter, "Show Midi Parameters");
                    if (showMidiParameter)
                    {
                        EditorGUILayout.BeginHorizontal();
                        EditorGUILayout.LabelField(new GUIContent("Quantization", ""), GUILayout.Width(150));
                        int newLevel = EditorGUILayout.Popup(instance.MPTK_Quantization, popupQuantization);
                        if (newLevel != instance.MPTK_Quantization && newLevel >= 0 && newLevel < popupQuantization.Length)
                        {
                            instance.MPTK_Quantization = newLevel;
                        }
                        EditorGUILayout.EndHorizontal();
                        EditorGUILayout.BeginHorizontal();
                        instance.MPTK_EnableChangeTempo = EditorGUILayout.Toggle(new GUIContent("Enable Tempo Change", "Enable midi event tempo change when playing"), instance.MPTK_EnableChangeTempo);
                        EditorGUILayout.LabelField(new GUIContent("Current:" + Math.Round(instance.MPTK_Tempo, 0), "Current tempo defined in Midi"));
                        EditorGUILayout.EndHorizontal();
                        instance.MPTK_EnablePanChange = EditorGUILayout.Toggle(new GUIContent("Enable Pan Change", "Enable midi event pan change when playing"), instance.MPTK_EnablePanChange);
                        instance.MPTK_KeepNoteOff     = EditorGUILayout.Toggle(new GUIContent("Keep Midi NoteOff", "Keep Midi NoteOff and NoteOn with Velocity=0 (need to restart the playing Midi)"), instance.MPTK_KeepNoteOff);
                        instance.MPTK_LogEvents       = EditorGUILayout.Toggle(new GUIContent("Log Midi Events", "Log information about each midi events read"), instance.MPTK_LogEvents);
                    }

                    showMidiInfo = EditorGUILayout.Foldout(showMidiInfo, "Show Midi Info");
                    if (showMidiInfo)
                    {
                        if (!string.IsNullOrEmpty(instance.MPTK_SequenceTrackName))
                        {
                            if (taSequence == null)
                            {
                                taSequence = new TextArea("Sequence");
                            }
                            taSequence.Display(instance.MPTK_SequenceTrackName);
                        }

                        if (!string.IsNullOrEmpty(instance.MPTK_ProgramName))
                        {
                            if (taProgram == null)
                            {
                                taProgram = new TextArea("Program");
                            }
                            taProgram.Display(instance.MPTK_ProgramName);
                        }

                        if (!string.IsNullOrEmpty(instance.MPTK_TrackInstrumentName))
                        {
                            if (taInstrument == null)
                            {
                                taInstrument = new TextArea("Instrument");
                            }
                            taInstrument.Display(instance.MPTK_TrackInstrumentName);
                        }

                        if (!string.IsNullOrEmpty(instance.MPTK_TextEvent))
                        {
                            if (taText == null)
                            {
                                taText = new TextArea("TextEvent");
                            }
                            taText.Display(instance.MPTK_TextEvent);
                        }

                        if (!string.IsNullOrEmpty(instance.MPTK_Copyright))
                        {
                            if (taCopyright == null)
                            {
                                taCopyright = new TextArea("Copyright");
                            }
                            taCopyright.Display(instance.MPTK_Copyright);
                        }
                    }

                    showEvents = EditorGUILayout.Foldout(showEvents, "Show Events");
                    if (showEvents)
                    {
                        EditorGUILayout.PropertyField(CustomEventStartPlayMidi);
                        EditorGUILayout.PropertyField(CustomEventListNotesEvent);
                        EditorGUILayout.PropertyField(CustomEventEndPlayMidi);
                        serializedObject.ApplyModifiedProperties();
                    }


                    //showDefault = EditorGUILayout.Foldout(showDefault, "Show default editor");
                    //if (showDefault) DrawDefaultInspector();
                }
                else
                {
                    EditorGUILayout.LabelField(new GUIContent("SoundFont: " + soundFontSelected, "Define SoundFont from the menu 'Tools/MPTK - SoundFont Setup' or alt-f"));
                    ToolsEditor.LoadMidiSet();
                    ToolsEditor.CheckMidiSet();
                }

                if (GUI.changed)
                {
                    EditorUtility.SetDirty(instance);
                }
            }
            catch (System.Exception ex)
            {
                MidiPlayerGlobal.ErrorDetail(ex);
            }
        }
        /// <summary>
        /// Display optimization
        /// </summary>
        /// <param name="localstartX"></param>
        /// <param name="localstartY"></param>
        private void ShowOptim(float localstartX, float localstartY, float width, float height)
        {
            try
            {
                Rect zone = new Rect(localstartX, localstartY, width, height);
                GUI.color = new Color(.8f, .8f, .8f, 1f);
                GUI.Box(zone, "");
                GUI.color = Color.white;

                string tooltip = "Remove all banks and Presets not used in the Midi file list";

                GUIContent content;
                if (MidiPlayerGlobal.ImSFCurrent != null)
                {
                    float xpos = localstartX + xpostitlebox;
                    float ypos = localstartY + ypostitlebox;
                    content = new GUIContent()
                    {
                        text = "Extract Patchs & Waves from " + MidiPlayerGlobal.ImSFCurrent.SoundFontName, tooltip = tooltip
                    };
                    EditorGUI.LabelField(new Rect(xpos, ypos, 380 + 85, itemHeight), content, styleBold);
                    ypos += itemHeight;// + espace;

                    if (MidiPlayerGlobal.ImSFCurrent.PatchCount == 0 || MidiPlayerGlobal.ImSFCurrent.WaveCount == 0)
                    {
                        EditorGUI.LabelField(new Rect(xpos, ypos, 380 + 85, itemHeight), "No patchs and waves has been yet extracted from the Soundfont.", styleRed);
                        ypos += itemHeight / 1f; // + espace;
                        EditorGUI.LabelField(new Rect(xpos, ypos, 380 + 85, itemHeight), "On the right panel, select one bank for instruments and", styleRed);
                        ypos += itemHeight / 2f; // + espace;
                        EditorGUI.LabelField(new Rect(xpos, ypos, 380 + 85, itemHeight), "optional, one bank for drums kit, others banks will be removed.", styleRed);
                        ypos += itemHeight / 1f; // + espace;
                        EditorGUI.LabelField(new Rect(xpos, ypos, 380 + 85, itemHeight), "Then, choose between 'Optimize from Midi file list'", styleRed);
                        ypos += itemHeight / 2f; // + espace;
                        EditorGUI.LabelField(new Rect(xpos, ypos, 380 + 85, itemHeight), "or 'Extract all Patchs & Waves' with the buttons below.", styleRed);

                        ypos += itemHeight;// + espace;
                    }
                    else
                    {
                        string infoSf = string.Format("Patch count: {0}   Wave count:{1}   Wave size:{2}",
                                                      MidiPlayerGlobal.ImSFCurrent.PatchCount,
                                                      MidiPlayerGlobal.ImSFCurrent.WaveCount,
                                                      (MidiPlayerGlobal.ImSFCurrent.WaveSize < 1000000) ?
                                                      Math.Round((double)MidiPlayerGlobal.ImSFCurrent.WaveSize / 1000d).ToString() + " Ko"
                                :
                                                      Math.Round((double)MidiPlayerGlobal.ImSFCurrent.WaveSize / 1000000d).ToString() + " Mo"
                                                      );
                        EditorGUI.LabelField(new Rect(xpos, ypos, 380 + 85, itemHeight), infoSf);

                        ypos += 2 * heightLine;
                    }
                    int widthCheck = 110;

                    /*
                     * KeepAllZones = GUI.Toggle(new Rect(xpos, ypos, widthCheck, itemHeight), KeepAllZones, new GUIContent("Keep all Zones", "Keep all Waves associated with a Patch regardless of notes and velocities played in Midi files.\n Usefull if you want transpose Midi files."));
                     * xpos += widthCheck + espace;
                     * KeepAllPatchs = GUI.Toggle(new Rect(xpos, ypos, widthCheck, itemHeight), KeepAllPatchs, new GUIContent("Keep all Patchs", "Keep all Patchs and waves found in the SoundFont selected.\nWarning : a huge volume of files coud be created"));
                     * xpos += widthCheck + +2 * espace;
                     * RemoveUnusedWaves = GUI.Toggle(new Rect(xpos, ypos, widthCheck + 40, itemHeight), RemoveUnusedWaves, new GUIContent("Remove unused waves", "If check, keep only waves used by your midi files"));
                     * ypos += itemHeight;// + espace;
                     */

                    // Always true
                    RemoveUnusedWaves = true;
                    xpos = localstartX + xpostitlebox;
                    Rect rect = new Rect(xpos, ypos, widthCheck * 2 + espace, buttonHeight);
#if MPTK_PRO
                    if (GUI.Button(rect, new GUIContent("Optimize from Midi file list", "Your list of Midi files will be scanned to identify patchs and zones useful")))
                    {
                        KeepAllPatchs = false;
                        KeepAllZones  = false;
                        OptimInfo     = new BuilderInfo();
                        SoundFontOptim.OptimizeSFFromMidiFiles(OptimInfo, KeepAllPatchs, KeepAllZones, RemoveUnusedWaves);
                        //listPatchs = PatchOptim.PatchUsed();
                    }

                    xpos += 3 * espace + 2 * widthCheck;
                    rect  = new Rect(xpos, ypos, buttonWidth, buttonHeight);
                    if (GUI.Button(rect, new GUIContent("Extract all Patchs & Waves", "All patchs and waves will be extracted from the Soundfile")))
                    {
                        KeepAllPatchs = true;
                        KeepAllZones  = true;
                        OptimInfo     = new BuilderInfo();
                        SoundFontOptim.OptimizeSFFromMidiFiles(OptimInfo, KeepAllPatchs, KeepAllZones, RemoveUnusedWaves);
                        //listPatchs = PatchOptim.PatchUsed();
                    }
#else
                    if (GUI.Button(rect, new GUIContent("Optimize from Midi file list [PRO]", "You need to setup some midi files before to launch ths optimization")))
                    {
                        PopupWindow.Show(rect, new GetVersionPro());
                    }
                    xpos += 3 * espace + 2 * widthCheck;
                    rect  = new Rect(xpos, ypos, buttonWidth, buttonHeight);
                    if (GUI.Button(rect, new GUIContent("Extract all Patchs & Waves [PRO]", "")))
                    {
                        PopupWindow.Show(rect, new GetVersionPro());
                    }
#endif
                    ypos += itemHeight + espace;


                    if (MidiPlayerGlobal.ImSFCurrent.PatchCount != 0 && MidiPlayerGlobal.ImSFCurrent.WaveCount != 0)
                    {
                        //
                        // Show patch list
                        //
                        xpos = localstartX + xpostitlebox;
                        EditorGUI.LabelField(new Rect(xpos, ypos, 380, itemHeight), "List of available Patchs:");
                        ypos += itemHeight / 2f;
                        List <string> patchList = new List <string>();
                        for (int i = 0; i < MidiPlayerGlobal.MPTK_ListPreset.Count; i++)
                        {
                            if (!string.IsNullOrEmpty(MidiPlayerGlobal.MPTK_ListPreset[i]))
                            {
                                patchList.Add(string.Format("Instrument - Patch: [{0:000}] {1}", i, MidiPlayerGlobal.MPTK_ListPreset[i]));
                            }
                        }
                        for (int i = 0; i < MidiPlayerGlobal.MPTK_ListDrum.Count; i++)
                        {
                            if (!string.IsNullOrEmpty(MidiPlayerGlobal.MPTK_ListDrum[i]))
                            {
                                patchList.Add(string.Format("Drum - Midi note: [{0:000}] {1}", i, MidiPlayerGlobal.MPTK_ListDrum[i]));
                            }
                        }

                        float heightAvailable = height - (ypos - (localstartY + ypostitlebox)) - 16;
                        Rect  listVisibleRect = new Rect(localstartX, ypos, width - 5, heightAvailable);
                        GUI.color = new Color(.8f, .8f, .8f, 1f);
                        GUI.Box(new Rect(localstartX + 5, ypos + 5, width - 30, heightAvailable - 4), "");
                        Rect listContentRect = new Rect(0, 0, width - 20, patchList.Count * itemHeight + 5);

                        scrollPosListPatchs = GUI.BeginScrollView(listVisibleRect, scrollPosListPatchs, listContentRect);
                        float boxY = 0;

                        foreach (string patchInfo in patchList)
                        {
                            GUI.color = new Color(.7f, .7f, .7f, 1f);
                            float boxX = 5;
                            GUI.Box(new Rect(boxX, boxY + 5, width - 30, itemHeight), "");
                            GUI.color = Color.white;
                            EditorGUI.LabelField(new Rect(boxX, boxY + 9, 300, itemHeight), patchInfo);
                            boxY += itemHeight;
                        }
                        GUI.EndScrollView();


                        ypos += heightAvailable + heightLine;



                        //List<PatchOptim> listPatchs = PatchOptim.PatchUsed();

                        //float heightAvailable = height - (ypos - (localstartY + ypostitlebox)) - 15 - 4 * heightLine;
                        //Rect listVisibleRect = new Rect(localstartX, ypos, width - 5, heightAvailable);
                        //Rect listContentRect = new Rect(0, 0, width - 20, listPatchs.Count * itemHeight + 5);

                        //scrollPosListPatchs = GUI.BeginScrollView(listVisibleRect, scrollPosListPatchs, listContentRect);
                        //float boxY = 0;

                        //for (int i = 0; i < listPatchs.Count; i++)
                        //{
                        //    GUI.color = new Color(.7f, .7f, .7f, 1f);
                        //    float boxX = 5;
                        //    GUI.Box(new Rect(boxX, boxY + 5, width - 30, itemHeight), "");
                        //    GUI.color = Color.white;
                        //    PatchOptim patch = listPatchs[i];
                        //    string patchinfo = string.Format("{0,15} [{1:000}] {2}", patch.Drum?"Drum":"Instrument", patch.Patch, patch.Name);
                        //    //content = new GUIContent() { text = patchinfo, tooltip = MidiPlayerGlobal.CurrentMidiSet.MidiFiles[i] };
                        //    EditorGUI.LabelField(new Rect(boxX, boxY + 9, 200, itemHeight), patchinfo);

                        //    //boxX += 280 + espace;
                        //    //patch.Selected = GUI.Toggle(new Rect(boxX, boxY + 9, 80, buttonHeight), patch.Selected, "Selected");

                        //    boxY += itemHeight;
                        //}
                        //GUI.EndScrollView();
                        //ypos += heightAvailable + heightLine;
                    }
                    //
                    // Show stat
                    //
                    //EditorGUI.LabelField(new Rect(localstartX + xpostitlebox, ypos, 100, heightLine), "Patch count :");
                    //EditorGUI.LabelField(new Rect(localstartX + xpostitlebox + 110, ypos, 100, heightLine), MidiPlayerGlobal.ImSFCurrent.PatchCount.ToString());
                    //ypos += heightLine;

                    //string strSize = "";
                    //if (MidiPlayerGlobal.ImSFCurrent.WaveSize < 1000000)
                    //    strSize = Math.Round((double)MidiPlayerGlobal.ImSFCurrent.WaveSize / 1000d).ToString() + " Ko";
                    //else
                    //    strSize = Math.Round((double)MidiPlayerGlobal.ImSFCurrent.WaveSize / 1000000d).ToString() + " Mo";

                    //EditorGUI.LabelField(new Rect(localstartX + xpostitlebox, ypos, 100, heightLine), "Wave count :");
                    //EditorGUI.LabelField(new Rect(localstartX + xpostitlebox + 110, ypos, 100, heightLine), MidiPlayerGlobal.ImSFCurrent.WaveCount.ToString());
                    //ypos += heightLine;

                    //EditorGUI.LabelField(new Rect(localstartX + xpostitlebox, ypos, 100, heightLine), "Wave size :");
                    //EditorGUI.LabelField(new Rect(localstartX + xpostitlebox + 110, ypos, 100, heightLine), strSize);
                    //ypos += heightLine;
                }
                else
                {
                    content = new GUIContent()
                    {
                        text = "No SoundFont selected", tooltip = tooltip
                    };
                    EditorGUI.LabelField(new Rect(localstartX + xpostitlebox, localstartY + ypostitlebox, 300, itemHeight), content, styleBold);
                }
            }
            catch (Exception ex)
            {
                MidiPlayerGlobal.ErrorDetail(ex);
            }
        }
Ejemplo n.º 10
0
        /// <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 = MidiPlayerGlobal.CurrentMidiSet.MidiFiles[i], tooltip = MidiPlayerGlobal.CurrentMidiSet.MidiFiles[i]
                        };
                        EditorGUI.LabelField(new Rect(boxX, boxY + 9, 200, itemHeight), content);

                        boxX += 200 + 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);
            }
        }
Ejemplo n.º 11
0
        public override void OnGUI(Rect rect)
        {
            try
            {
                float xCol0     = 5;
                float xCol1     = 20;
                float xCol2     = 120;
                float yStart    = 5;
                float ySpace    = 18;
                float colWidth  = 230;
                float colHeight = 17;

                GUIStyle style = new GUIStyle("Label");
                style.fontSize  = 16;
                style.fontStyle = FontStyle.Bold;

                try
                {
                    int     sizePicture = 90;
                    Texture aTexture    = Resources.Load <Texture>("Logo_MPTK");
                    EditorGUI.DrawPreviewTexture(new Rect(winWidth - sizePicture - 5, yStart, sizePicture, sizePicture), aTexture);
                }
                catch (System.Exception ex)
                {
                    MidiPlayerGlobal.ErrorDetail(ex);
                }
                GUIContent cont = new GUIContent("Midi Player ToolKit (MPTK)");
                EditorGUI.LabelField(new Rect(xCol0, yStart, 300, 30), cont, style);
                EditorGUI.LabelField(new Rect(xCol0, yStart + 8, 300, colHeight), "_________________________________");

                yStart += 15;
                EditorGUI.LabelField(new Rect(xCol1, yStart += ySpace, colWidth, colHeight), "Version:");
                EditorGUI.LabelField(new Rect(xCol2, yStart, colWidth, colHeight), ToolsEditor.version);

                EditorGUI.LabelField(new Rect(xCol1, yStart += ySpace, colWidth, colHeight), "Release:");
                EditorGUI.LabelField(new Rect(xCol2, yStart, colWidth, colHeight), ToolsEditor.releaseDate);

                yStart += 15;
                EditorGUI.LabelField(new Rect(xCol0, yStart += ySpace, colWidth, colHeight), "Developed by Thierry Bachmann");
                EditorGUI.LabelField(new Rect(xCol1, yStart += ySpace, colWidth, colHeight), "Email:");
                EditorGUI.TextField(new Rect(xCol2, yStart, colWidth, colHeight), "*****@*****.**");
                EditorGUI.LabelField(new Rect(xCol1, yStart += ySpace, colWidth, colHeight), "Website:");
                EditorGUI.TextField(new Rect(xCol2, yStart, colWidth, colHeight), ToolsEditor.paxSite);

                yStart  += 30;
                colWidth = 110;
                int space = 8;
                if (GUI.Button(new Rect(xCol0, yStart, colWidth, colHeight), "Open Web Site"))
                {
                    Application.OpenURL(ToolsEditor.paxSite);
                }
                if (GUI.Button(new Rect(xCol0 + colWidth + space, yStart, colWidth, colHeight), "Help"))
                {
                    Application.OpenURL(ToolsEditor.blogSite);
                }

                if (GUI.Button(new Rect(xCol0 + colWidth + space + colWidth + space, yStart, colWidth, colHeight), "Get Full Version"))
                {
                    Application.OpenURL(ToolsEditor.UnitySite);
                }
            }
            catch (System.Exception ex)
            {
                MidiPlayerGlobal.ErrorDetail(ex);
            }
        }
Ejemplo n.º 12
0
        public override void OnInspectorGUI()
        {
            try
            {
                GUI.changed = false;
                GUI.color   = Color.white;
                styleBold   = new GUIStyle("Label")
                {
                    fontSize  = 12,
                    fontStyle = FontStyle.Bold
                };

                string soundFontSelected = "No SoundFont selected.";
                if (MidiPlayerGlobal.CurrentMidiSet != null && MidiPlayerGlobal.CurrentMidiSet.ActiveSounFontInfo != null)
                {
                    soundFontSelected = MidiPlayerGlobal.CurrentMidiSet.ActiveSounFontInfo.Name;
                    EditorGUILayout.LabelField(new GUIContent("SoundFont: " + MidiPlayerGlobal.CurrentMidiSet.ActiveSounFontInfo.Name, "Define SoundFont from the menu 'Tools/MPTK - SoundFont Setup' or alt-f"));
                    //       EditorGUILayout.Separator();

                    instance.MidiStreamPlayer = (MidiStreamPlayer)EditorGUILayout.ObjectField(new GUIContent("Midi Stream Player"), instance.MidiStreamPlayer, typeof(MidiStreamPlayer), true);

                    ObjType = instance.GetType();
                    instance.MeasureLength    = UtToolsEditor.IntSlider("Mesure Length", "Quarter number per measure", "MeasureLength", instance.MeasureLength, ObjType);
                    instance.QuarterPerMinute = UtToolsEditor.IntSlider("Quarter Per Minute", "Quarter Per Minute", "QuarterPerMinute", instance.QuarterPerMinute, ObjType);

                    //
                    // Running
                    //
                    if (Application.isPlaying)
                    {
                        EditorGUILayout.LabelField(new GUIContent("Measure", ""),
                                                   new GUIContent(string.Format("{0,3:000}.{1,2:00}.{2,2:00}",
                                                                                InfinityMusic.instance.IndexMeasure + 1, InfinityMusic.instance.IndexQuarterMeasure + 1, InfinityMusic.instance.IndexSixteenthMeasure + 1), ""), styleBold);
                    }

                    //
                    // Actions
                    //
                    if (Application.isPlaying)
                    {
                        instance.SongName    = EditorGUILayout.TextField(new GUIContent("Song Name", ""), instance.SongName);
                        instance.Description = EditorGUILayout.TextArea(instance.Description);

                        EditorGUILayout.Space();
                        EditorGUILayout.LabelField(new GUIContent("Song", ""));
                        EditorGUILayout.BeginHorizontal();
                        if (GUILayout.Button(new GUIContent("New"), GUILayout.ExpandWidth(true)))
                        {
                            if (EditorUtility.DisplayDialog("New Song", "Erase current song ?", "Ok", "Cancel"))
                            {
                                InfinityMusic.UtNewSong();
                            }
                        }

                        if (GUILayout.Button(new GUIContent("Save"), GUILayout.ExpandWidth(true)))
                        {
                            string path = Path.Combine(Application.dataPath, MidiPlayerGlobal.PathToSong);
                            if (!Directory.Exists(path))
                            {
                                Directory.CreateDirectory(path);
                            }

                            string filepath = EditorUtility.SaveFilePanel("Save Song", path, null, MidiPlayerGlobal.ExtensionSong);
                            if (!string.IsNullOrEmpty(filepath))
                            {
                                SaveLoad.UtSave(filepath);
                            }
                        }

                        if (GUILayout.Button(new GUIContent("Open"), GUILayout.ExpandWidth(true)))
                        {
                            string path = EditorUtility.OpenFilePanel("Open Song", Path.Combine(Application.dataPath, MidiPlayerGlobal.PathToSong), MidiPlayerGlobal.ExtensionSong);
                            if (!string.IsNullOrEmpty(path))
                            {
                                InfinityMusic.UtNewSong();
                                SaveLoad.UtLoad(path);
                            }
                        }
                        EditorGUILayout.EndHorizontal();
                        EditorGUILayout.Space();

                        EditorGUILayout.LabelField(new GUIContent("Create components", ""));
                        EditorGUILayout.BeginHorizontal();
                        if (GUILayout.Button(new GUIContent("Math Motif", ""), GUILayout.ExpandWidth(true)))
                        {
                            UtComponent.UtNew(UtComponent.Component.Motif);
                        }
                        if (GUILayout.Button(new GUIContent("Cadence", ""), GUILayout.ExpandWidth(true)))
                        {
                            UtComponent.UtNew(UtComponent.Component.Cadence);
                        }
                        EditorGUILayout.EndHorizontal();
                    }
                    else
                    {
                        //if (GUILayout.Button(new GUIContent("View folder", ""), GUILayout.ExpandWidth(false)))
                        //    EditorUtility.RevealInFinder(UtGlobal.BuildPathConfig(null));
                    }
                }
                else
                {
                    EditorGUILayout.LabelField(new GUIContent("SoundFont: " + soundFontSelected, "Define SoundFont from the menu 'Tools/MPTK - SoundFont Setup' or alt-f"));
                    ToolsEditor.LoadMidiSet();
                    ToolsEditor.CheckMidiSet();
                }

                showDefault = EditorGUILayout.Foldout(showDefault, "Show default editor");
                if (showDefault)
                {
                    DrawDefaultInspector();
                }

                if (GUI.changed)
                {
                    EditorUtility.SetDirty(instance);
                }
            }
            catch (System.Exception ex)
            {
                MidiPlayerGlobal.ErrorDetail(ex);
            }
        }
Ejemplo n.º 13
0
        public override void OnInspectorGUI()
        {
            try
            {
                GUI.changed = false;
                GUI.color   = Color.white;
                styleBold   = new GUIStyle("Label")
                {
                    fontSize  = 12,
                    fontStyle = FontStyle.Bold
                };


                int MeasureCount = EditorGUILayout.IntSlider(new GUIContent("Measure"), instance.MeasureCount, 1, 8);
                if (MeasureCount != instance.MeasureCount)
                {
                    instance.MeasureCount = MeasureCount;
                    instance.Generate(true);
                }
                instance.CurrentCadence = (UtCadence)EditorGUILayout.ObjectField(new GUIContent("Cadence"), instance.CurrentCadence, typeof(UtCadence), true);

                instance.DrumKit = EditorGUILayout.Toggle(new GUIContent("Drum Kit", ""), instance.DrumKit);
                if (!instance.DrumKit)
                {
                    if (list != null)
                    {
                        instance.PatchIndex = EditorGUILayout.Popup("Patch", instance.PatchIndex, list);
                    }
                    else
                    {
                        EditorGUILayout.LabelField(new GUIContent("No patchs (wave) found", ""));
                    }
                }

                //
                // Scale
                //
                EditorGUILayout.LabelField(new GUIContent("Scale", "Used a predefined scale"));
                EditorGUI.indentLevel++;
                int ScaleIndex = EditorGUILayout.Popup("Select", instance.ScaleIndex, ScaleDefinition.Names.ToArray());
                if (ScaleIndex != instance.ScaleIndex)
                {
                    instance.ScaleIndex = ScaleIndex;
                    instance.Generate(true);
                }
                int StepInScale = EditorGUILayout.IntSlider(new GUIContent("Step In Scale", "With 1 get all notes in scale, with n get note each n"), instance.StepInScale, 1, 10);
                if (StepInScale != instance.StepInScale)
                {
                    instance.StepInScale = StepInScale;
                    instance.Generate(true);
                }
                EditorGUI.indentLevel--;

                //
                // Volume
                //
                EditorGUILayout.LabelField(new GUIContent("Volume note", ""));
                EditorGUI.indentLevel++;
                instance.Velocity     = EditorGUILayout.IntSlider(new GUIContent("Velocity", "Volume of the note played"), instance.Velocity, 0, 127);
                instance.Accentuation = EditorGUILayout.IntSlider(new GUIContent("Accentuation", "Increases the volume by percent on the first note of the measure"), instance.Accentuation, 0, 100);
                EditorGUI.indentLevel--;

                //
                // Generator
                //
                EditorGUILayout.LabelField(new GUIContent("Generator", ""));
                EditorGUI.indentLevel++;
                int SelectedAlgo = EditorGUILayout.Popup("Algo", (int)instance.SelectedAlgo, Enum.GetNames(typeof(Mode)));
                if (SelectedAlgo != (int)instance.SelectedAlgo)
                {
                    instance.SelectedAlgo = (Mode)SelectedAlgo;
                    instance.Generate(true);
                }

                int octave = EditorGUILayout.IntSlider(new GUIContent("Octave min", "Octave for starting generating notes"), instance.OctaveMin, 0, 10);
                if (octave != instance.OctaveMin)
                {
                    instance.OctaveMin = octave;
                    instance.Generate(true);
                }

                octave = EditorGUILayout.IntSlider(new GUIContent("Octave max", "Octave for ending generating notes"), instance.OctaveMax, 0, 10);
                if (octave != instance.OctaveMax)
                {
                    instance.OctaveMax = octave;
                    instance.Generate(true);
                }
                instance.Transpose = EditorGUILayout.IntSlider(new GUIContent("Transpose", "Transpose of the note played"), instance.Transpose, -48, 48);

                if (instance.SelectedAlgo == Mode.CircleDown || instance.SelectedAlgo == Mode.CircleUp)
                {
                    instance.RotationSpeed = EditorGUILayout.IntSlider(new GUIContent("Rotation", "Rotation speed for Circle algo"), instance.RotationSpeed, -500, 500);
                }

                int RepeatRate = EditorGUILayout.IntSlider(new GUIContent("Repeat rate", "Repeat rate of the last notes played"), instance.RepeatRate, 0, 100);
                if (RepeatRate != instance.RepeatRate)
                {
                    instance.RepeatRate = RepeatRate;
                    instance.Generate(true);
                }
                EditorGUI.indentLevel--;

                //
                // Running
                //
                if (Application.isPlaying)
                {
                    EditorGUILayout.LabelField(new GUIContent("Measure", ""),
                                               new GUIContent(string.Format("{0,3:000}.{1,2:00}.{2,2:00}",
                                                                            InfinityMusic.instance.IndexMeasure + 1, InfinityMusic.instance.IndexQuarterMeasure + 1, InfinityMusic.instance.IndexSixteenthMeasure + 1), ""), styleBold);
                    EditorGUILayout.LabelField(new GUIContent("Played Note", ""),
                                               new GUIContent(string.Format("{0,3:000} / {1,3:000}", instance.CurrentIndexNotePlayed, instance.Score != null ? instance.Score.Length : 0), ""), styleBold);
                }

                //
                // Actions
                //
                if (Application.isPlaying)
                {
                    EditorGUILayout.Space();
                    EditorGUILayout.BeginHorizontal();
                    if (GUILayout.Button(new GUIContent("Generate", ""), GUILayout.ExpandWidth(false)))
                    {
                        instance.Generate(true);
                    }
                    if (GUILayout.Button(new GUIContent("Set To Default", "Restore default value"), GUILayout.ExpandWidth(false)))
                    {
                        instance.DefaultValue();
                        instance.Generate(true);
                    }
                    EditorGUILayout.EndHorizontal();
                }

                showDefault = EditorGUILayout.Foldout(showDefault, "Show default editor");
                if (showDefault)
                {
                    DrawDefaultInspector();
                }


                if (GUI.changed)
                {
                    EditorUtility.SetDirty(instance);
                }
            }
            catch (System.Exception ex)
            {
                MidiPlayerGlobal.ErrorDetail(ex);
            }
        }
Ejemplo n.º 14
0
        private List <TrackMidiEvent> GetEvents()
        {
            try
            {
                List <TrackMidiEvent> events = new List <TrackMidiEvent>();
                foreach (IList <MidiEvent> track in midifile.Events)
                {
                    CountTracks++;
                    foreach (MidiEvent e in track)
                    {
                        try
                        {
                            if (e.Channel > 0 && e.Channel <= 16)
                            {
                                Chanels[e.Channel - 1] = true;
                            }

                            bool keepEvent = false;
                            switch (e.CommandCode)
                            {
                            case MidiCommandCode.NoteOn:
                                //Debug.Log("NoteOn");
                                if (KeepNoteOff)
                                {
                                    // keep note even if no offevent
                                    keepEvent = true;
                                }
                                else
                                if (((NoteOnEvent)e).OffEvent != null)
                                {
                                    keepEvent = true;
                                }
                                break;

                            case MidiCommandCode.NoteOff:
                                //Debug.Log("NoteOff");
                                if (KeepNoteOff)
                                {
                                    keepEvent = true;
                                }
                                break;

                            case MidiCommandCode.ControlChange:
                                //ControlChangeEvent ctrl = (ControlChangeEvent)e;
                                //Debug.Log("NoteOff");
                                keepEvent = true;
                                break;

                            case MidiCommandCode.PatchChange:
                                keepEvent = true;
                                break;

                            case MidiCommandCode.MetaEvent:
                                MetaEvent meta = (MetaEvent)e;
                                switch (meta.MetaEventType)
                                {
                                case MetaEventType.SetTempo:
                                    // Set the first tempo value find
                                    //if (QuarterPerMinuteValue < 0d)
                                    //Debug.Log("MicrosecondsPerQuarterNote:"+((TempoEvent)e).MicrosecondsPerQuarterNote);
                                    ChangeTempo(((TempoEvent)e).Tempo);
                                    break;
                                }
                                keepEvent = true;
                                break;
                            }
                            if (keepEvent)
                            {
                                events.Add(new TrackMidiEvent()
                                {
                                    IndexTrack = CountTracks, Event = e.Clone()
                                });
                            }
                        }
                        catch (System.Exception ex)
                        {
                            MidiPlayerGlobal.ErrorDetail(ex);
                            //List<TrackMidiEvent> MidiSorted = events.OrderBy(o => o.Event.AbsoluteTime).ToList();
                            return(events.OrderBy(o => o.Event.AbsoluteTime).ToList());
                        }
                    }
                }

                /// Sort midi event by time
                List <TrackMidiEvent> MidiSorted = events.OrderBy(o => o.Event.AbsoluteTime).ToList();
                return(MidiSorted);
            }
            catch (System.Exception ex)
            {
                MidiPlayerGlobal.ErrorDetail(ex);
            }
            return(null);
        }
Ejemplo n.º 15
0
        public List <MidiNote> ReadMidiEvents(double timeFromStartMS)
        {
            List <MidiNote> notes = null;

            try
            {
                EndMidiEvent = false;
                if (midifile != null)
                {
                    if (NextPosEvent < MidiSorted.Count)
                    {
                        // 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)
                        // Calculate current pulse to play
                        CurrentPulse += Convert.ToInt64((timeFromStartMS - LastTimeFromStartMS) / PulseLengthMs);

                        LastTimeFromStartMS = timeFromStartMS;

                        // From the last position played
                        for (int currentPosEvent = NextPosEvent; currentPosEvent < MidiSorted.Count; currentPosEvent++)
                        {
                            TrackMidiEvent trackEvent = MidiSorted[currentPosEvent];
                            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 <= CurrentPulse)
                            {
                                NextPosEvent = currentPosEvent + 1;

                                if (trackEvent.Event.CommandCode == MidiCommandCode.NoteOn)
                                {
                                    if (((NoteOnEvent)trackEvent.Event).OffEvent != null)
                                    {
                                        NoteOnEvent noteon = (NoteOnEvent)trackEvent.Event;
                                        // if (noteon.OffEvent != null)
                                        {
                                            if (notes == null)
                                            {
                                                notes = new List <MidiNote>();
                                            }

                                            //Debug.Log(string.Format("Track:{0} NoteNumber:{1,3:000} AbsoluteTime:{2,6:000000} NoteLength:{3,6:000000} OffDeltaTime:{4,6:000000} ", track, noteon.NoteNumber, noteon.AbsoluteTime, noteon.NoteLength, noteon.OffEvent.DeltaTime));
                                            MidiNote note = new MidiNote()
                                            {
                                                AbsoluteQuantize = trackEvent.AbsoluteQuantize,
                                                Midi             = noteon.NoteNumber,
                                                Channel          = trackEvent.Event.Channel,
                                                Velocity         = noteon.Velocity,
                                                Duration         = noteon.NoteLength * PulseLengthMs,
                                                Length           = noteon.NoteLength,
                                                Patch            = PatchChanel[trackEvent.Event.Channel - 1],
                                                Drum             = (trackEvent.Event.Channel == 10),
                                                Delay            = 0,
                                                Pan = EnablePanChange ? PanChanel[trackEvent.Event.Channel - 1] : -1,
                                            };
                                            if (VolumeChanel[note.Channel - 1] != 127)
                                            {
                                                note.Velocity = Mathf.RoundToInt(((float)note.Velocity) * ((float)VolumeChanel[trackEvent.Event.Channel - 1]) / 127f);
                                            }
                                            notes.Add(note);
                                            if (LogEvents)
                                            {
                                                Debug.Log(BuildInfoTrack(trackEvent) + string.Format("{0,-4} {1,3:000} Lenght:{2} {3} Veloc:{4}",
                                                                                                     noteon.NoteName, noteon.NoteNumber, noteon.NoteLength, NoteLength(note), noteon.Velocity));
                                            }
                                        }
                                    }
                                }
                                else if (trackEvent.Event.CommandCode == MidiCommandCode.NoteOff)
                                {
                                    // no need, noteoff are associated with noteon
                                }
                                else if (trackEvent.Event.CommandCode == MidiCommandCode.ControlChange)
                                {
                                    ControlChangeEvent controlchange = (ControlChangeEvent)trackEvent.Event;
                                    if (controlchange.Controller == MidiController.Expression)
                                    {
                                        VolumeChanel[trackEvent.Event.Channel - 1] = controlchange.ControllerValue;
                                    }
                                    else if (controlchange.Controller == MidiController.MainVolume)
                                    {
                                        VolumeChanel[trackEvent.Event.Channel - 1] = controlchange.ControllerValue;
                                    }
                                    else if (controlchange.Controller == MidiController.Pan)
                                    {
                                        PanChanel[trackEvent.Event.Channel - 1] = controlchange.ControllerValue;
                                    }
                                    // Other midi event
                                    if (LogEvents)
                                    {
                                        Debug.Log(BuildInfoTrack(trackEvent) + string.Format("Control {0} {1}", controlchange.Controller, controlchange.ControllerValue));
                                    }
                                }
                                else if (trackEvent.Event.CommandCode == MidiCommandCode.PatchChange)
                                {
                                    PatchChangeEvent change = (PatchChangeEvent)trackEvent.Event;
                                    PatchChanel[trackEvent.Event.Channel - 1] = trackEvent.Event.Channel == 10 ? 0 : change.Patch;
                                    if (LogEvents)
                                    {
                                        Debug.Log(BuildInfoTrack(trackEvent) + string.Format("Patch   {0,3:000} {1}", change.Patch, PatchChangeEvent.GetPatchName(change.Patch)));
                                    }
                                }
                                else if (trackEvent.Event.CommandCode == MidiCommandCode.MetaEvent)
                                {
                                    MetaEvent meta = (MetaEvent)trackEvent.Event;
                                    switch (meta.MetaEventType)
                                    {
                                    case MetaEventType.SetTempo:
                                        if (EnableChangeTempo)
                                        {
                                            TempoEvent tempo = (TempoEvent)meta;
                                            //NewQuarterPerMinuteValue = tempo.Tempo;
                                            ChangeTempo(tempo.Tempo);
                                            //if (LogEvents)Debug.Log(BuildInfoTrack(trackEvent) + string.Format("SetTempo   {0} MicrosecondsPerQuarterNote:{1}", tempo.Tempo, tempo.MicrosecondsPerQuarterNote));
                                        }
                                        break;

                                    case MetaEventType.SequenceTrackName:
                                        if (!string.IsNullOrEmpty(SequenceTrackName))
                                        {
                                            SequenceTrackName += "\n";
                                        }
                                        SequenceTrackName += string.Format("T{0,2:00} {1}", trackEvent.IndexTrack, ((TextEvent)meta).Text);
                                        if (LogEvents)
                                        {
                                            Debug.Log(BuildInfoTrack(trackEvent) + string.Format("Sequence   '{0}'", ((TextEvent)meta).Text));
                                        }
                                        break;

                                    case MetaEventType.ProgramName:
                                        ProgramName += ((TextEvent)meta).Text + " ";
                                        if (LogEvents)
                                        {
                                            Debug.Log(BuildInfoTrack(trackEvent) + string.Format("Program   '{0}'", ((TextEvent)meta).Text));
                                        }
                                        break;

                                    case MetaEventType.TrackInstrumentName:
                                        if (!string.IsNullOrEmpty(TrackInstrumentName))
                                        {
                                            TrackInstrumentName += "\n";
                                        }
                                        TrackInstrumentName += string.Format("T{0,2:00} {1}", trackEvent.IndexTrack, ((TextEvent)meta).Text);
                                        if (LogEvents)
                                        {
                                            Debug.Log(BuildInfoTrack(trackEvent) + string.Format("Text      '{0}'", ((TextEvent)meta).Text));
                                        }
                                        break;

                                    case MetaEventType.TextEvent:
                                        TextEvent += ((TextEvent)meta).Text + " ";
                                        if (LogEvents)
                                        {
                                            Debug.Log(BuildInfoTrack(trackEvent) + string.Format("Sequence  '{0}'", ((TextEvent)meta).Text));
                                        }
                                        break;

                                    case MetaEventType.Copyright:
                                        Copyright += ((TextEvent)meta).Text + " ";
                                        if (LogEvents)
                                        {
                                            Debug.Log(BuildInfoTrack(trackEvent) + string.Format("Copyright '{0}'", ((TextEvent)meta).Text));
                                        }
                                        break;

                                    case MetaEventType.Lyric:     // lyric
                                    case MetaEventType.Marker:    // marker
                                    case MetaEventType.CuePoint:  // cue point
                                    case MetaEventType.DeviceName:
                                        break;
                                    }
                                    //Debug.Log(BuildInfoTrack(trackEvent) + string.Format("Meta {0} {1}", meta.MetaEventType, meta.ToString()));
                                }
                                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
                            {
                                // Out of time, exit for loop
                                break;
                            }
                        }

                        if (notes != null)
                        {
                            //if (CancelNextReadEvents)
                            //{
                            //    notes = null;
                            //    //Debug.Log("CancelNextReadEvents");
                            //    CancelNextReadEvents = false;
                            //}
                            //else
                            //if (notes.Count > 3 && (notes[notes.Count - 1].AbsoluteQuantize - notes[0].AbsoluteQuantize) > midifile.DeltaTicksPerQuarterNote * 8)
                            //{
                            //    //notes.RemoveRange(0, notes.Count - 1);
                            //    Debug.Log("--> Too much notes " + notes.Count + " timeFromStartMS:" + Convert.ToInt32(timeFromStartMS) + " Start:" + notes[0].AbsoluteQuantize + " Ecart:" + (notes[notes.Count - 1].AbsoluteQuantize - notes[0].AbsoluteQuantize) + " CurrentPulse:" + CurrentPulse);
                            //    //notes = null;
                            //}
                        }
                    }
                    else
                    {
                        // End of midi events
                        EndMidiEvent = true;
                    }
                }
            }
            catch (System.Exception ex)
            {
                MidiPlayerGlobal.ErrorDetail(ex);
            }
            return(notes);
        }
Ejemplo n.º 16
0
        public override void Generate(bool fake)
        {
            try
            {
                int indexCadence = 0;
                Durations = new List <Cadence>();
                Debug.Log("Generate Cadence");
                for (int measure = 0; measure < MeasureCount; measure++)
                {
                    int countSixteen = 16; // Always the max else : Global.instance.countSixteenthMeasure;

                    // Generate for the maximum : 4 measures
                    while (countSixteen > 0)
                    {
                        Cadence.Duration enDuration = Cadence.Duration.NotDefined;

                        float randDuration = UnityEngine.Random.Range(1f, 100f);

                        if (randDuration < RatioWhole)
                        {
                            enDuration = Cadence.Duration.Whole;
                        }
                        if (randDuration < RatioHalf)
                        {
                            enDuration = Cadence.Duration.Half;
                        }
                        if (randDuration < RatioQuarter)
                        {
                            enDuration = Cadence.Duration.Quarter;
                        }
                        if (randDuration < RatioEighth)
                        {
                            enDuration = Cadence.Duration.Eighth;
                        }
                        if (randDuration < RatioSixteen)
                        {
                            enDuration = Cadence.Duration.Sixteenth;
                        }
                        if (enDuration == Cadence.Duration.NotDefined)
                        {
                            enDuration = Cadence.Duration.Quarter;
                        }

                        countSixteen -= MathMotifNote.NbrOfSixteen(enDuration);

                        float randSilence = UnityEngine.Random.Range(1f, 100f);

                        Cadence cadence = new Cadence()
                        {
                            enDuration = enDuration, Silence = randSilence >= PctSilence ? false : true
                        };
                        //Debug.Log("   cadence:" + indexCadence + " measure:" + measure + " countSixteen:" + countSixteen + " enDuration:" + cadence.enDuration + " Silence:" + cadence.Silence);
                        Durations.Add(cadence);
                        indexCadence++;
                    }
                }

                LastCadenceGenerated = DateTime.Now;
            }
            catch (System.Exception ex)
            {
                MidiPlayerGlobal.ErrorDetail(ex);
            }
        }
Ejemplo n.º 17
0
        public override void OnInspectorGUI()
        {
            try
            {
                GUI.changed = false;
                GUI.color   = Color.white;
                styleBold   = new GUIStyle("Label")
                {
                    fontSize  = 12,
                    fontStyle = FontStyle.Bold
                };

                EditorGUILayout.Space();
                EditorGUILayout.BeginHorizontal();
                if (GUILayout.Button(new GUIContent("+", ""), GUILayout.ExpandWidth(false)))
                {
                    instance.Components.Add(null);
                }
                EditorGUILayout.EndHorizontal();

                for (int i = 0; i < instance.Components.Count; i++)
                {
                    EditorGUILayout.BeginHorizontal();
                    instance.Components[i] = (UtComponent)EditorGUILayout.ObjectField(new GUIContent("Component"), instance.Components[i], typeof(UtComponent), true);
                    if (GUILayout.Button(new GUIContent("-", ""), GUILayout.ExpandWidth(false)))
                    {
                        instance.Components.Add(null);
                    }
                    EditorGUILayout.EndHorizontal();
                }
                //for (int i = 0; i < instance.Components.Count;)
                //    if (instance.Components[i] == null)
                //        instance.Components.RemoveAt(i);
                //    else
                //        i++;

                //var reorderableList = new UnityEditorInternal.ReorderableList(instance.Components, typeof(UtMathMotif), true, true, true, true);
                ////reorderableList.DoList(rect);
                ////or
                //reorderableList.DoLayoutList();

                //
                // Running
                //
                if (Application.isPlaying)
                {
                    EditorGUILayout.LabelField(new GUIContent("Measure", ""),
                                               new GUIContent(string.Format("{0,3:000}.{1,2:00}.{2,2:00}",
                                                                            InfinityMusic.instance.IndexMeasure + 1, InfinityMusic.instance.IndexQuarterMeasure + 1, InfinityMusic.instance.IndexSixteenthMeasure + 1), ""), styleBold);
                }

                //
                // Actions
                //
                if (Application.isPlaying)
                {
                    EditorGUILayout.Space();
                    EditorGUILayout.BeginHorizontal();
                    if (GUILayout.Button(new GUIContent("Generate", ""), GUILayout.ExpandWidth(false)))
                    {
                        instance.Generate(false);
                    }
                    EditorGUILayout.EndHorizontal();
                }

                showDefault = EditorGUILayout.Foldout(showDefault, "Show default editor");
                if (showDefault)
                {
                    DrawDefaultInspector();
                }

                if (GUI.changed)
                {
                    EditorUtility.SetDirty(instance);
                }
            }
            catch (System.Exception ex)
            {
                MidiPlayerGlobal.ErrorDetail(ex);
            }
        }
Ejemplo n.º 18
0
        static public void UtLoad(string songname)
        {
            SaveLoad slSong;

            Debug.Log(">>> Load");
            lock (InfinityMusic.instance)
            {
                try
                {
                    slSong = SaveLoad.LoadXML(songname);
                    if (slSong != null)
                    {
                        // Cadence
                        //Debug.Log("Cadence Count:" + slSong.Cadences.Count);
                        foreach (ImCadence im in slSong.Cadences)
                        {
                            Debug.Log(" " + im.Name);
                            UtCadence ut = (UtCadence)InfinityMusic.Instantiate(InfinityMusic.instance.TemplateCadence, Vector3.zero, Quaternion.identity);
                            ut.transform.parent = InfinityMusic.instance.transform;
                            // Common
                            LoadCommon(im, ut);

                            // Specific
                            ut.MeasureCount = im.MeasureCount;
                            ut.PctSilence   = im.PctSilence;
                            ut.RatioWhole   = im.RatioWhole;
                            ut.RatioHalf    = im.RatioHalf;
                            ut.RatioQuarter = im.RatioQuarter;
                            ut.RatioEighth  = im.RatioEighth;
                            ut.RatioSixteen = im.RatioSixteen;
                            ut.Durations    = (im.Durations != null && im.Durations.Count > 0) ? new List <Cadence>(im.Durations) : null;
                        }


                        // Math Motif
                        Debug.Log("Math Motif Count:" + slSong.Motifs.Count);
                        foreach (ImMathMotif im in slSong.Motifs)
                        {
                            //Debug.Log(" " + im.Name);
                            UtMathMotif ut = (UtMathMotif)InfinityMusic.Instantiate(InfinityMusic.instance.TemplateMathMotif, Vector3.zero, Quaternion.identity);
                            ut.transform.parent = InfinityMusic.instance.transform;

                            // Common
                            LoadCommon(im, ut);

                            // Specific
                            ut.MeasureCount  = im.MeasureCount;
                            ut.OctaveMin     = im.OctaveMin;
                            ut.OctaveMax     = im.OctaveMax;
                            ut.ScaleIndex    = im.ScaleIndex;
                            ut.PatchIndex    = im.PatchIndex;
                            ut.DrumKit       = im.DrumKit;
                            ut.SelectedAlgo  = im.SelectedAlgo;
                            ut.StepInScale   = im.StepInScale;
                            ut.RotationSpeed = im.RotationSpeed;
                            ut.Accentuation  = im.Accentuation;
                            ut.Velocity      = im.Velocity;
                            ut.RepeatRate    = im.RepeatRate;
                            if (im.IdCadence >= 0)
                            {
                                UtCadence[] cadences = GameObject.FindObjectsOfType <UtCadence>();
                                foreach (UtCadence cadence in cadences)
                                {
                                    if (cadence.UtId == im.IdCadence)
                                    {
                                        ut.CurrentCadence = cadence;
                                        break;
                                    }
                                }
                            }
                            ut.Notes = (im.Notes != null && im.Notes.Count > 0) ? new List <MathMotifNote>(im.Notes) : null;
                        }

                        //Debug.Log("Chorder Count:" + slSong.Chorders.Count);
                        //foreach (ImChorder im in slSong.Chorders)
                        //{
                        //    Debug.Log(" " + im.ImName + " " + im.ImRadiusEffect);
                        //    UtChorder ut = (UtChorder)Instantiate(UtGlobal.instance.utChorder, im.Position, Quaternion.identity);

                        //    // Common
                        //    LoadCommon(im, ut);

                        //    // Specific
                        //    ut.Trigger = im.Trigger;
                        //    ut.StepCount = im.StepCount;
                        //    ut.ChordProgression = im.ChordProgression;
                        //}


                        //// Midi Motif
                        //Debug.Log("Midi Motif Count:" + slSong.Midis.Count);
                        //foreach (ImMidiMotif im in slSong.Midis)
                        //{
                        //    Debug.Log(" " + im.ImName + " " + im.ImRadiusEffect);
                        //    UtMidiMotif ut = (UtMidiMotif)Instantiate(UtGlobal.instance.utMidiMotif, im.Position, Quaternion.identity);

                        //    // Common
                        //    LoadCommon(im, ut);

                        //    // Specific
                        //    ut.MidiName = im.MidiName;
                        //    ut.Transpose = im.Transpose;
                        //    ut.StartPlay = im.StartPlay;
                        //    ut.EndPlay = im.EndPlay;
                        //    ut.DeltaTicksPerQuarterNote = im.DeltaTicksPerQuarterNote;
                        //    ut.NumberBeatsMeasure = im.NumberBeatsMeasure;
                        //    ut.NumberQuarterBeat = im.NumberQuarterBeat;
                        //    ut.SelectedMode = im.SelectedMode;
                        //    ut.StepPlay = im.StepPlay;
                        //    //ut.MidiMeasures = im.Measures;
                        //    ut.Tracks = im.Tracks;
                        //    ut.ImportTracksToMeasure();
                        //}

                        ////
                        //// Modifier
                        ////
                        //Debug.Log("Modifier Count:" + slSong.Modifiers.Count);
                        //foreach (ImModifier im in slSong.Modifiers)
                        //{
                        //    Debug.Log(">>> Create '" + im.ImName + "'");
                        //    UtModifier ut = (UtModifier)Instantiate(UtGlobal.instance.utModifier, im.Position, Quaternion.identity);
                        //    //Debug.Log("<<< Create '" + im.ImName + "'");

                        //    // Common
                        //    LoadCommon(im, ut);

                        //    // Specific
                        //    ut.MeasureCount = im.MeasureCount;
                        //    ut.SelectedMode = im.SelectedMode;

                        //    //if (im.IndexProperties < 5)
                        //    //{
                        //    //    ut.IndexApplyTo = 1;
                        //    //    ut.IndexProperties = im.IndexProperties;

                        //    //}
                        //    //else
                        //    //{
                        //    //    ut.IndexApplyTo = 0;
                        //    //    ut.IndexProperties = 0;
                        //    //}
                        //    ut.IndexApplyTo = im.IndexApplyTo;
                        //    ut.IndexProperties = im.IndexProperties;

                        //    //Debug.Log("   im.MinSelected " + im.MinSelected);
                        //    //Debug.Log("   im.MaxSelected " + im.MaxSelected);
                        //    ut.FromSelected = im.MinSelected;
                        //    ut.ToSelected = im.MaxSelected;
                        //    ut.Step = im.Step;
                        //}

                        ////
                        //// Drum
                        ////
                        //Debug.Log("Drum Count:" + slSong.Drums.Count);
                        //foreach (ImDrum im in slSong.Drums)
                        //{
                        //    Debug.Log(">>> Create '" + im.ImName + "'");
                        //    UtDrum ut = (UtDrum)Instantiate(UtGlobal.instance.utDrum, im.Position, Quaternion.identity);
                        //    //Debug.Log("<<< Create '" + im.ImName + "'");

                        //    // Common
                        //    LoadCommon(im, ut);

                        //    // Specific
                        //    ut.Tracks = im.Tracks;
                        //    ut.RandomLevel = im.RandomLevel;
                        //}

                        ////
                        //// Activator
                        ////
                        //Debug.Log("Activator Count:" + slSong.Activators.Count);
                        //foreach (ImActivator im in slSong.Activators)
                        //{
                        //    Debug.Log(">>> Create '" + im.ImName + "'");
                        //    UtActivator ut = (UtActivator)Instantiate(UtGlobal.instance.utActivator, im.Position, Quaternion.identity);
                        //    //Debug.Log("<<< Create '" + im.ImName + "'");

                        //    // Common
                        //    LoadCommon(im, ut);

                        //    // Specific
                        //    ut.MeasureCount = im.MeasureCount;
                        //    ut.MeasureStart = im.MeasureStart;
                        //    ut.ActivateBeforeStart = im.ActivateBeforeStart;
                        //    ut.ActivateAfterLoop = im.ActivateAfterLoop;
                        //    ut.LoopCount = im.LoopCount;
                        //    ut.Activates = im.Activates;
                        //}


                        InfinityMusic.instance.MeasureLength    = slSong.MeasureLength;
                        InfinityMusic.instance.QuarterPerMinute = slSong.QuarterPerMinute;
                        InfinityMusic.instance.MaxMeasure       = slSong.MaxMeasure;
                        if (InfinityMusic.instance.MaxMeasure <= 0)
                        {
                            InfinityMusic.instance.MaxMeasure = 1000;
                        }
                        InfinityMusic.instance.SongName    = slSong.SongName;
                        InfinityMusic.instance.Description = slSong.Description;
                    }
                }
                catch (System.Exception ex)
                {
                    MidiPlayerGlobal.ErrorDetail(ex);
                }
            }
            Debug.Log("<<< Load");
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Update list SoundFont and Midi
        /// </summary>
        public static void CheckMidiSet()
        {
            // Activate one time to renum all the midi files in resource folder
            //RenumMidiFile();

            //
            // Check Soundfont
            //
            try
            {
                string folder = Path.Combine(Application.dataPath + "/", MidiPlayerGlobal.PathToSoundfonts);
                if (Directory.Exists(folder))
                {
                    bool     tobesaved   = false;
                    string[] fileEntries = Directory.GetFiles(folder, "*" + MidiPlayerGlobal.ExtensionSoundFileFile, SearchOption.AllDirectories);

                    // Check if sf has been removed by user in resource
                    int isf = 0;
                    while (isf < MidiPlayerGlobal.CurrentMidiSet.SoundFonts.Count)
                    {
                        bool found = false;
                        foreach (string filepath in fileEntries)
                        {
                            if (filepath.Contains(MidiPlayerGlobal.CurrentMidiSet.SoundFonts[isf].Name))
                            {
                                found = true;
                            }
                        }
                        if (!found)
                        {
                            MidiPlayerGlobal.CurrentMidiSet.SoundFonts.RemoveAt(isf);
                            tobesaved = true;
                        }
                        else
                        {
                            isf++;
                        }
                    }

                    // Active sound font exists in midiset ?
                    if (MidiPlayerGlobal.CurrentMidiSet != null && MidiPlayerGlobal.ImSFCurrent != null)
                    {
                        if (MidiPlayerGlobal.CurrentMidiSet.SoundFonts != null && MidiPlayerGlobal.CurrentMidiSet.SoundFonts.Find(s => s.Name == MidiPlayerGlobal.ImSFCurrent.SoundFontName) == null)
                        {
                            // no the current SF has been remove from resource, define first SF  as active or nothing if no SF exists
                            if (MidiPlayerGlobal.CurrentMidiSet.SoundFonts.Count >= 0)
                            {
                                MidiPlayerGlobal.CurrentMidiSet.SetActiveSoundFont(0);
                                LoadImSF();
                            }
                            else
                            {
                                MidiPlayerGlobal.CurrentMidiSet.SetActiveSoundFont(-1);
                            }
                            tobesaved = true;
                        }
                    }
                    if (tobesaved)
                    {
                        MidiPlayerGlobal.CurrentMidiSet.Save();
                    }
                }
            }
            catch (System.Exception ex)
            {
                MidiPlayerGlobal.ErrorDetail(ex);
            }

            try
            {
                string pathMidi = Path.Combine(Application.dataPath, MidiPlayerGlobal.PathToMidiFile);
                if (!Directory.Exists(pathMidi))
                {
                    Directory.CreateDirectory(pathMidi);
                }

                RenameExtFileFromMidToBytes();

                //
                // Check Midifile : remove from DB midifile removed from resource
                //
                bool          tobesaved = false;
                List <string> midiFiles = GetMidiFilePath();
                int           im        = 0;
                while (im < MidiPlayerGlobal.CurrentMidiSet.MidiFiles.Count)
                {
                    bool found = false;
                    foreach (string filepath in midiFiles)
                    {
                        if (filepath.Contains(MidiPlayerGlobal.CurrentMidiSet.MidiFiles[im]))
                        {
                            found = true;
                        }
                    }
                    if (!found)
                    {
                        MidiPlayerGlobal.CurrentMidiSet.MidiFiles.RemoveAt(im);
                        tobesaved = true;
                    }
                    else
                    {
                        im++;
                    }
                }

                //
                // Check Midifile : Add to DB midifile found from resource
                //
                foreach (string pathmidifile in midiFiles)
                {
                    string filename = Path.GetFileNameWithoutExtension(pathmidifile);
                    if (MidiPlayerGlobal.CurrentMidiSet.MidiFiles.FindIndex(s => s == filename) < 0)
                    {
                        tobesaved = true;
                        MidiPlayerGlobal.CurrentMidiSet.MidiFiles.Add(filename);
                    }
                }

                if (tobesaved)
                {
                    MidiPlayerGlobal.CurrentMidiSet.MidiFiles.Sort();
                    MidiPlayerGlobal.CurrentMidiSet.Save();
                }
            }
            catch (System.Exception ex)
            {
                MidiPlayerGlobal.ErrorDetail(ex);
            }
        }
Ejemplo n.º 20
0
        public override void OnGUI(Rect rect)
        {
            try
            {
                float xCol0     = 5;
                float xCol1     = 20;
                float xCol2     = 120;
                float yStart    = 5;
                float ySpace    = 18;
                float colWidth  = 230;
                float colHeight = 17;

                GUIStyle style16Bold = new GUIStyle("Label");
                style16Bold.fontSize  = 16;
                style16Bold.fontStyle = FontStyle.Bold;

                GUIStyle styleBold = new GUIStyle("Label");
                styleBold.fontStyle = FontStyle.Bold;

                try
                {
                    int     sizePicture = 90;
                    Texture aTexture    = Resources.Load <Texture>("Logo_MPTK");
                    EditorGUI.DrawPreviewTexture(new Rect(winWidth - sizePicture - 5, yStart, sizePicture, sizePicture), aTexture);
                }
                catch (System.Exception ex)
                {
                    MidiPlayerGlobal.ErrorDetail(ex);
                }
                GUIContent cont = new GUIContent("Midi Player ToolKit (MPTK)");
                EditorGUI.LabelField(new Rect(xCol0, yStart, 300, 30), cont, style16Bold);
                EditorGUI.LabelField(new Rect(xCol0, yStart + 8, 300, colHeight), "_________________________________");

                yStart += 20;
                EditorGUI.LabelField(new Rect(xCol0, yStart += ySpace, colWidth, colHeight), "This fonctionality is not available", styleBold);
                EditorGUI.LabelField(new Rect(xCol0, yStart += ySpace, colWidth, colHeight), "        with the free version", styleBold);
                yStart += 25;
                EditorGUI.LabelField(new Rect(xCol0, yStart += ySpace, colWidth + 20, colHeight), "The pro version includes these capacities :");
                // yStart += 15;

                EditorGUI.LabelField(new Rect(xCol1, yStart += ySpace, colWidth, colHeight), "- Import SoundFont");
                EditorGUI.LabelField(new Rect(xCol1, yStart += ySpace, colWidth, colHeight), "- Create simplified soundfont");
                EditorGUI.LabelField(new Rect(xCol1, yStart += ySpace, colWidth, colHeight), "- Remove unused wavefile");
                yStart += 30;
                EditorGUI.LabelField(new Rect(xCol1, yStart, colWidth, colHeight), "Website:");
                EditorGUI.TextField(new Rect(xCol2, yStart, colWidth, colHeight), ToolsEditor.paxSite);
                yStart += 30;

                colWidth = 110;
                int space = 8;
                if (GUI.Button(new Rect(xCol0, yStart, colWidth, colHeight), "Open Web Site"))
                {
                    Application.OpenURL(ToolsEditor.paxSite);
                }
                if (GUI.Button(new Rect(xCol0 + colWidth + space, yStart, colWidth, colHeight), "Help"))
                {
                    Application.OpenURL(ToolsEditor.blogSite);
                }

                if (GUI.Button(new Rect(xCol0 + colWidth + space + colWidth + space, yStart, colWidth, colHeight), "Get Full Version"))
                {
                    Application.OpenURL(ToolsEditor.UnitySite);
                    //EditorUtility.DisplayDialog("Not yet Available", "Pro version not yet available. Soon ....", "Ok");
                }
            }
            catch (System.Exception ex)
            {
                MidiPlayerGlobal.ErrorDetail(ex);
            }
        }
Ejemplo n.º 21
0
        /// <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.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 Soundfont
        /// </summary>
        /// <param name="localstartX"></param>
        /// <param name="localstartY"></param>
        private void ShowListSoundFonts(float localstartX, float localstartY, float width, float height)
        {
            try
            {
                Rect zone = new Rect(localstartX, localstartY, width, height);
                GUI.color = new Color(.8f, .8f, .8f, 1f);
                GUI.Box(zone, "");
                GUI.color = Color.white;
                if (MidiPlayerGlobal.CurrentMidiSet != null && MidiPlayerGlobal.CurrentMidiSet.SoundFonts != null)
                {
                    string caption = "SoundFont available";
                    if (MidiPlayerGlobal.CurrentMidiSet.SoundFonts.Count == 0)
                    {
                        caption = "No SoundFont available yet";
                        MidiPlayerGlobal.ImSFCurrent = null;
                    }

                    GUIContent content = new GUIContent()
                    {
                        text = caption, tooltip = "Each SoundFonts contains a set of bank of sound. \nOnly one SoundFont can be active at the same time for the midi player"
                    };
                    EditorGUI.LabelField(new Rect(localstartX + xpostitlebox, localstartY + ypostitlebox, 300, itemHeight), content, styleBold);
                    Rect rect = new Rect(width - buttonWidth, localstartY + ypostitlebox, buttonWidth, buttonHeight);
#if MPTK_PRO
                    if (GUI.Button(rect, "Add SoundFont"))
                    {
                        //if (EditorUtility.DisplayDialog("Import SoundFont", "This action could take time, do you confirm ?", "Ok", "Cancel"))
                        {
                            SoundFontOptim.AddSoundFont();
                            scrollPosSoundFont = Vector2.zero;
                            KeepAllPatchs      = false;
                            KeepAllZones       = false;
                            //listPatchs = PatchOptim.PatchUsed();
                        }
                    }
#else
                    if (GUI.Button(rect, "Add SoundFont [PRO]"))
                    {
                        try
                        {
                            PopupWindow.Show(rect, new GetVersionPro());
                        }
                        catch (Exception)
                        {
                            // generate some weird exception ...
                        }
                    }
#endif

                    Rect listVisibleRect = new Rect(localstartX, localstartY + itemHeight, width - 5, height - itemHeight - 5);
                    Rect listContentRect = new Rect(0, 0, width - 20, MidiPlayerGlobal.CurrentMidiSet.SoundFonts.Count * itemHeight + 5);

                    scrollPosSoundFont = GUI.BeginScrollView(listVisibleRect, scrollPosSoundFont, listContentRect);
                    float boxY = 0;

                    for (int i = 0; i < MidiPlayerGlobal.CurrentMidiSet.SoundFonts.Count; i++)
                    {
                        SoundFontInfo sf = MidiPlayerGlobal.CurrentMidiSet.SoundFonts[i];

                        GUI.color = new Color(.7f, .7f, .7f, 1f);
                        float boxX = 5;
                        GUI.Box(new Rect(boxX, boxY + 5, width - 30, itemHeight), "");
                        GUI.color = Color.white;

                        content = new GUIContent()
                        {
                            text = sf.Name, tooltip = ""
                        };
                        EditorGUI.LabelField(new Rect(boxX, boxY + 9, 200, itemHeight), content);

                        if (sf.Name == MidiPlayerGlobal.CurrentMidiSet.ActiveSounFontInfo.Name)
                        {
                            GUI.color = ToolsEditor.ButtonColor;
                        }

                        boxX += 200 + espace;
                        if (GUI.Button(new Rect(boxX, boxY + 9, 80, buttonHeight), "Select"))
                        {
#if MPTK_PRO
                            OptimInfo = new BuilderInfo();
#endif
                            MidiPlayerGlobal.CurrentMidiSet.SetActiveSoundFont(i);
                            string soundPath = Path.Combine(Application.dataPath + "/", MidiPlayerGlobal.PathToSoundfonts);
                            soundPath = Path.Combine(soundPath + "/", sf.Name);
                            ToolsEditor.LoadImSF(soundPath, sf.Name);
                            MidiPlayerGlobal.CurrentMidiSet.Save();
                            if (MidiPlayerGlobal.ImSFCurrent != null)
                            {
                                KeepAllPatchs     = MidiPlayerGlobal.ImSFCurrent.KeepAllPatchs;
                                KeepAllZones      = MidiPlayerGlobal.ImSFCurrent.KeepAllZones;
                                RemoveUnusedWaves = MidiPlayerGlobal.ImSFCurrent.RemoveUnusedWaves;
                                if (Application.isPlaying)
                                {
                                    MidiPlayerGlobal.MPTK_SelectSoundFont(null);
                                }
                            }
                            //listPatchs = PatchOptim.PatchUsed();
                        }
                        boxX += 80 + espace;

                        GUI.color = Color.white;
                        rect      = new Rect(boxX, boxY + 9, 80, buttonHeight);
                        if (GUI.Button(rect, "Remove"))
                        {
#if MPTK_PRO
                            OptimInfo = new BuilderInfo();
                            string soundFontPath = Path.Combine(Application.dataPath + "/", MidiPlayerGlobal.PathToSoundfonts);
                            string path          = Path.Combine(soundFontPath, sf.Name);
                            if (!string.IsNullOrEmpty(path) && EditorUtility.DisplayDialog("Delete SoundFont", "Are you sure to delete all the content of this folder ? " + path, "ok", "cancel"))
                            {
                                try
                                {
                                    Directory.Delete(path, true);
                                    File.Delete(path + ".meta");
                                }
                                catch (Exception ex)
                                {
                                    Debug.Log("Remove SF " + ex.Message);
                                }
                                AssetDatabase.Refresh();
                                ToolsEditor.CheckMidiSet();
                            }
#else
                            try
                            {
                                PopupWindow.Show(rect, new GetVersionPro());
                            }
                            catch (Exception)
                            {
                                // generate some weird exception ...
                            }
#endif
                        }

                        GUI.color = Color.white;

                        //boxX = 5;
                        //boxY += itemHeight;
                        //if (MidiPlayerGlobal.ImSFCurrent.WaveSize < 1000000)
                        //    strSize = Math.Round((double)MidiPlayerGlobal.ImSFCurrent.WaveSize / 1000d).ToString() + " Ko";
                        //else
                        //    strSize = Math.Round((double)MidiPlayerGlobal.ImSFCurrent.WaveSize / 1000000d).ToString() + " Mo";
                        //string.Format("Patch count: {0} Wave count:{1} Wave size:{2}", MidiPlayerGlobal.ImSFCurrent.PatchCount, MidiPlayerGlobal.ImSFCurrent.WaveCount, strSize);

                        //content = new GUIContent() { text = sf.Name, tooltip = "" };
                        //EditorGUI.LabelField(new Rect(boxX, boxY + 9, 200, itemHeight), content);

                        boxY += itemHeight;
                    }
                    GUI.EndScrollView();
                }
            }
            catch (Exception ex)
            {
                MidiPlayerGlobal.ErrorDetail(ex);
            }
        }
Ejemplo n.º 23
0
        public void OnGUI()
        {
            try
            {
                if (customSkin != null)
                {
                    GUI.skin = customSkin;
                }
                if (myStyle == null)
                {
                    myStyle = new CustomStyle();
                }


                GUI.changed = false;
                GUI.color   = Color.white;
                //GUIStyle styleBold;
                //styleBold = new GUIStyle("Label")
                //{
                //    fontSize = 12,
                //    fontStyle = FontStyle.Bold
                //};

                float widthSelectSong = 200;
                float buttonHeight    = 30;
                float buttonWidth     = 200;
                float listHeight      = 150;
                float maxwidth        = Screen.width / 2;
                if (maxwidth < 300)
                {
                    maxwidth = 300;
                }


                if (MidiPlayerGlobal.CurrentMidiSet != null && MidiPlayerGlobal.CurrentMidiSet.ActiveSounFontInfo != null)
                {
                    GUILayout.BeginArea(new Rect(25, 30, maxwidth, 600));

                    GUILayout.Label("InfinityMusic - Music generated by an algo", myStyle.TitleLabel1);
                    if (GUILayout.Button(new GUIContent("Return to menu", "")))
                    {
                        GoMainMenu.Go();
                    }
                    GUILayout.Space(20);

                    GUISelectSoundFont.Display(myStyle);

                    GUILayout.Space(20);
                    GUILayout.Label(
                        string.Format("Measure {0,3:000}.{1,2:00}.{2,2:00}", InfinityMusic.instance.IndexMeasure + 1, InfinityMusic.instance.IndexQuarterMeasure + 1, InfinityMusic.instance.IndexSixteenthMeasure + 1),
                        myStyle.TitleLabel2);
                    GUILayout.Space(20);
                    GUILayout.BeginHorizontal();

                    SelectSong(widthSelectSong, listHeight);

                    GUILayout.BeginVertical();

                    if (GUILayout.Button("New", GUILayout.Width(buttonWidth), GUILayout.Height(buttonHeight)))
                    {
                        GuiMessage = null;
                        InfinityMusic.UtNewSong();
                        instance.SongName = "";
                    }

                    if (GUILayout.Button("Open", GUILayout.Width(buttonWidth), GUILayout.Height(buttonHeight)))
                    {
                        if (string.IsNullOrEmpty(SelectedSongName))
                        {
                            GuiMessage = "Select a song name";
                        }
                        else
                        {
                            GuiMessage = null;
                            string path     = Path.Combine(Application.dataPath, MidiPlayerGlobal.PathToSong);
                            string filepath = Path.Combine(path, SelectedSongName + "." + MidiPlayerGlobal.ExtensionSong);
                            if (!string.IsNullOrEmpty(filepath))
                            {
                                instance.SongName = SelectedSongName;
                                InfinityMusic.UtNewSong();
                                SaveLoad.UtLoad(filepath);
                            }
                        }
                    }

                    instance.SongName = GUILayout.TextField(instance.SongName, GUILayout.Width(buttonWidth), GUILayout.Height(buttonHeight));

                    if (GUILayout.Button("Save", GUILayout.Width(buttonWidth), GUILayout.Height(buttonHeight)))
                    {
                        if (string.IsNullOrEmpty(instance.SongName))
                        {
                            GuiMessage = "Set a name for this song";
                        }
                        else
                        {
                            GuiMessage = null;

                            string path = Path.Combine(Application.dataPath, MidiPlayerGlobal.PathToSong);
                            if (!Directory.Exists(path))
                            {
                                Directory.CreateDirectory(path);
                            }

                            string filepath = Path.Combine(path, instance.SongName + "." + MidiPlayerGlobal.ExtensionSong);
                            if (!string.IsNullOrEmpty(filepath))
                            {
                                SaveLoad.UtSave(filepath);
                            }
                        }
                    }
                    GUILayout.EndVertical();

                    GUILayout.EndHorizontal();

                    GUILayout.BeginVertical();
                    if (!string.IsNullOrEmpty(GuiMessage))
                    {
                        GUI.color = Color.red;
                        GUILayout.Label(GuiMessage, myStyle.TitleLabel2);
                        GUI.color = Color.white;
                    }
                    GUILayout.Label("Go to your Hierarchy and select InfinityMusic:", myStyle.TitleLabel2);
                    GUILayout.Label("   - Add MathMotif or Cadence components by clicking on button.", myStyle.TitleLabel2);
                    GUILayout.Label("   - Select created components MathMotif or Cadence under InfinityMusic.", myStyle.TitleLabel2);
                    GUILayout.Label("   - Change parameters in inspector to change melody.", myStyle.TitleLabel2);
                    GUILayout.EndVertical();
                }
                else
                {
                    GUILayout.Label(new GUIContent("SoundFont: no soundfont selected", "Define SoundFont from the menu 'Tools/MPTK - SoundFont Setup' or alt-f"));
                }
                GUILayout.EndArea();
            }
            catch (System.Exception ex)
            {
                MidiPlayerGlobal.ErrorDetail(ex);
            }
        }
        private void ShowListBanks(float localstartX, float localstartY, float width, float height)
        {
            try
            {
                Rect zone = new Rect(localstartX, localstartY, width, height);
                GUI.color = new Color(.8f, .8f, .8f, 1f);
                GUI.Box(zone, "");
                GUI.color = Color.white;

                if (MidiPlayerGlobal.ImSFCurrent != null && MidiPlayerGlobal.ImSFCurrent.Banks != null)
                {
                    string     tooltip = "Each bank contains a set of patchs (instrument).\nOnly two banks can be active at the same time : default sound (piano, ...) and drum kit (percussive)";
                    GUIContent content = new GUIContent()
                    {
                        text = "Banks available in SoundFont " + MidiPlayerGlobal.ImSFCurrent.SoundFontName, tooltip = tooltip
                    };
                    //GUIContent content = new GUIContent() { text = "Banks available in SoundFont ", tooltip = tooltip };
                    EditorGUI.LabelField(new Rect(localstartX + xpostitlebox, localstartY + ypostitlebox, width, itemHeight), content, styleBold);

                    //if (GUI.Button(new Rect(localstartX + width - buttonWidth - espace, localstartY + ypostitlebox, buttonWidth, buttonHeight), new GUIContent() { text = "2) Removed not used", tooltip = tooltip }))
                    //{
                    //    SoundFontOptim.OptimizeBanks(MidiPlayerGlobal.ImSFCurrent);
                    //    MidiPlayerGlobal.CurrentMidiSet.Save();
                    //}

                    // Count available banks
                    int countBank = 0;
                    foreach (ImBank bank in MidiPlayerGlobal.ImSFCurrent.Banks)
                    {
                        if (bank != null)
                        {
                            countBank++;
                        }
                    }
                    Rect listVisibleRect = new Rect(localstartX, localstartY + itemHeight, width, height - itemHeight - 5);
                    Rect listContentRect = new Rect(0, 0, width - 15, countBank * itemHeight + 5);

                    scrollPosBanks = GUI.BeginScrollView(listVisibleRect, scrollPosBanks, listContentRect);

                    float         boxY = 0;
                    SoundFontInfo sfi  = MidiPlayerGlobal.CurrentMidiSet.ActiveSounFontInfo;
                    if (sfi != null)
                    {
                        foreach (ImBank bank in MidiPlayerGlobal.ImSFCurrent.Banks)
                        {
                            if (bank != null)
                            {
                                GUI.color = new Color(.7f, .7f, .7f, 1f);
                                GUI.Box(new Rect(5, boxY + 5, width - 25, itemHeight), "");

                                GUI.color = Color.white;

                                content = new GUIContent()
                                {
                                    text = string.Format("Bank [{0,3:000}] Patch:{1}", bank.BankNumber, bank.PatchCount), tooltip = bank.Description
                                };
                                GUI.Label(new Rect(10, boxY + 9, 130, itemHeight), content);

                                //Debug.Log(sfi.DefaultBankNumber );
                                if (sfi.DefaultBankNumber == bank.BankNumber)
                                {
                                    GUI.color = ToolsEditor.ButtonColor;
                                }
                                if (GUI.Button(new Rect(155, boxY + 9, 120, buttonHeight), new GUIContent("Default Bank", "Select this bank to be used for all instruments except drum")))
                                {
                                    sfi.DefaultBankNumber = sfi.DefaultBankNumber != bank.BankNumber ? bank.BankNumber : -1;
                                    MidiPlayerGlobal.ImSFCurrent.DefaultBankNumber = bank.BankNumber;
                                    MidiPlayerGlobal.CurrentMidiSet.Save();
                                }
                                GUI.color = Color.white;

                                if (sfi.DrumKitBankNumber == bank.BankNumber)
                                {
                                    GUI.color = ToolsEditor.ButtonColor;
                                }
                                if (GUI.Button(new Rect(155 + 120 + 5, boxY + 9, 120, buttonHeight), new GUIContent("Drum Bank", "Select this bank to be used for playing drum hit")))
                                {
                                    sfi.DrumKitBankNumber = sfi.DrumKitBankNumber != bank.BankNumber ? bank.BankNumber : -1;
                                    MidiPlayerGlobal.ImSFCurrent.DrumKitBankNumber = bank.BankNumber;
                                    MidiPlayerGlobal.CurrentMidiSet.Save();
                                }
                                GUI.color = Color.white;
                                boxY     += itemHeight;
                            }
                        }
                    }

                    GUI.EndScrollView();
                }
                else
                {
                    EditorGUI.LabelField(new Rect(localstartX + xpostitlebox, localstartY + ypostitlebox, 300, itemHeight), "No SoundFont selected", styleBold);
                }
            }
            catch (Exception ex)
            {
                MidiPlayerGlobal.ErrorDetail(ex);
            }
        }
Ejemplo n.º 25
0
        static public void Init()
        {
            try
            {
                ListEcart = new List <HelperNoteLabel>();
                ListEcart.Add(new HelperNoteLabel()
                {
                    Label = "C", Midi = 0,
                });
                ListEcart.Add(new HelperNoteLabel()
                {
                    Label = "C#", Midi = 1, Sharp = true,
                });
                ListEcart.Add(new HelperNoteLabel()
                {
                    Label = "D", Midi = 2,
                });
                ListEcart.Add(new HelperNoteLabel()
                {
                    Label = "D#", Midi = 3, Sharp = true,
                });
                ListEcart.Add(new HelperNoteLabel()
                {
                    Label = "E", Midi = 4,
                });
                ListEcart.Add(new HelperNoteLabel()
                {
                    Label = "F", Midi = 5,
                });
                ListEcart.Add(new HelperNoteLabel()
                {
                    Label = "F#", Midi = 6, Sharp = true,
                });
                ListEcart.Add(new HelperNoteLabel()
                {
                    Label = "G", Midi = 7,
                });
                ListEcart.Add(new HelperNoteLabel()
                {
                    Label = "G#", Midi = 8, Sharp = true,
                });
                ListEcart.Add(new HelperNoteLabel()
                {
                    Label = "A", Midi = 9,
                });
                ListEcart.Add(new HelperNoteLabel()
                {
                    Label = "A#", Midi = 10, Sharp = true,
                });
                ListEcart.Add(new HelperNoteLabel()
                {
                    Label = "B", Midi = 11,
                });

                ListNote = new List <HelperNoteLabel>();
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "C0", Midi = 0,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "C0#", Midi = 1, Sharp = true,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "D0", Midi = 2,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "D0#", Midi = 3, Sharp = true,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "E0", Midi = 4,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "F0", Midi = 5,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "F0#", Midi = 6, Sharp = true,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "G0", Midi = 7,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "G0#", Midi = 8, Sharp = true,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "A0", Midi = 9,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "A0#", Midi = 10, Sharp = true,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "B0", Midi = 11,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "C1", Midi = 12,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "C1#", Midi = 13, Sharp = true,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "D1", Midi = 14,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "D1#", Midi = 15, Sharp = true,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "E1", Midi = 16,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "F1", Midi = 17,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "F1#", Midi = 18, Sharp = true,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "G1", Midi = 19,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "G1#", Midi = 20, Sharp = true,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "A1", Midi = 21,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "A1#", Midi = 22, Sharp = true,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "B1", Midi = 23,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "C2", Midi = 24,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "C2#", Midi = 25, Sharp = true,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "D2", Midi = 26,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "D2#", Midi = 27, Sharp = true,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "E2", Midi = 28,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "F2", Midi = 29,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "F2#", Midi = 30, Sharp = true,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "G2", Midi = 31,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "G2#", Midi = 32, Sharp = true,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "A2", Midi = 33,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "A2#", Midi = 34, Sharp = true,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "B2", Midi = 35,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "C3", Midi = 36,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "C3#", Midi = 37, Sharp = true,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "D3", Midi = 38,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "D3#", Midi = 39, Sharp = true,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "E3", Midi = 40,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "F3", Midi = 41,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "F3#", Midi = 42, Sharp = true,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "G3", Midi = 43,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "G3#", Midi = 44, Sharp = true,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "A3", Midi = 45,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "A3#", Midi = 46, Sharp = true,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "B3", Midi = 47,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "C4", Midi = 48,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "C4#", Midi = 49, Sharp = true,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "D4", Midi = 50,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "D4#", Midi = 51, Sharp = true,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "E4", Midi = 52,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "F4", Midi = 53,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "F4#", Midi = 54, Sharp = true,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "G4", Midi = 55,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "G4#", Midi = 56, Sharp = true,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "A4", Midi = 57,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "A4#", Midi = 58, Sharp = true,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "B4", Midi = 59,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "C5", Midi = 60,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "C5#", Midi = 61, Sharp = true,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "D5", Midi = 62,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "D5#", Midi = 63, Sharp = true,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "E5", Midi = 64,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "F5", Midi = 65,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "F5#", Midi = 66, Sharp = true,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "G5", Midi = 67,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "G5#", Midi = 68, Sharp = true,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "A5", Midi = 69,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "A5#", Midi = 70, Sharp = true,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "B5", Midi = 71,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "C6", Midi = 72,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "C6#", Midi = 73, Sharp = true,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "D6", Midi = 74,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "D6#", Midi = 75, Sharp = true,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "E6", Midi = 76,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "F6", Midi = 77,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "F6#", Midi = 78, Sharp = true,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "G6", Midi = 79,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "G6#", Midi = 80, Sharp = true,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "A6", Midi = 81,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "A6#", Midi = 82, Sharp = true,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "B6", Midi = 83,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "C7", Midi = 84,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "C7#", Midi = 85, Sharp = true,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "D7", Midi = 86,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "D7#", Midi = 87, Sharp = true,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "E7", Midi = 88,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "F7", Midi = 89,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "F7#", Midi = 90, Sharp = true,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "G7", Midi = 91,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "G7#", Midi = 92, Sharp = true,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "A7", Midi = 93,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "A7#", Midi = 94, Sharp = true,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "B7", Midi = 95,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "C8", Midi = 96,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "C8#", Midi = 97, Sharp = true,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "D8", Midi = 98,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "D8#", Midi = 99, Sharp = true,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "E8", Midi = 100,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "F8", Midi = 101,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "F8#", Midi = 102, Sharp = true,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "G8", Midi = 103,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "G8#", Midi = 104, Sharp = true,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "A8", Midi = 105,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "A8#", Midi = 106, Sharp = true,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "B8", Midi = 107,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "C9", Midi = 108,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "C9#", Midi = 109, Sharp = true,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "D9", Midi = 110,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "D9#", Midi = 111, Sharp = true,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "E9", Midi = 112,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "F9", Midi = 113,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "F9#", Midi = 114, Sharp = true,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "G9", Midi = 115,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "G9#", Midi = 116, Sharp = true,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "A9", Midi = 117,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "A9#", Midi = 118, Sharp = true,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "B9", Midi = 119,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "C10", Midi = 120,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "C10#", Midi = 121, Sharp = true,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "D10", Midi = 122,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "D10#", Midi = 123, Sharp = true,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "E10", Midi = 124,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "F10", Midi = 125,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "F10#", Midi = 126, Sharp = true,
                });
                ListNote.Add(new HelperNoteLabel()
                {
                    Label = "G10", Midi = 127,
                });
            }
            catch (System.Exception ex)
            {
                MidiPlayerGlobal.ErrorDetail(ex);
            }
            // For test
            //ListNote[60].Ratio = 1f; // C3
            //ListNote[60].Frequence = 261.626f; // C3

            //foreach (HelperNote hn in ListNote)
            //{
            //    hn.Ratio = Mathf.Pow(_ratioHalfTone, hn.Midi);
            //    hn.Frequence = ListNote[48].Frequence * hn.Ratio;
            //    //Debug.Log("Position:" + hn.Position +" Hauteur:" + hn.Hauteur +" Label:" + hn.Label +" Ratio:" + hn.Ratio +" Frequence:" + hn.Frequence);
            //}
        }
Ejemplo n.º 26
0
        public override void OnInspectorGUI()
        {
            try
            {
                GUI.changed = false;
                GUI.color   = Color.white;

                //mDebug.Log(Event.current.type);

                string soundFontSelected = "No SoundFont selected.";
                if (MidiPlayerGlobal.CurrentMidiSet != null && MidiPlayerGlobal.CurrentMidiSet.ActiveSounFontInfo != null)
                {
                    soundFontSelected = MidiPlayerGlobal.CurrentMidiSet.ActiveSounFontInfo.Name;
                    EditorGUILayout.LabelField(new GUIContent("SoundFont: " + soundFontSelected, "Define SoundFont from the menu 'Tools/MPTK - SoundFont Setup' or alt-f"));
                    EditorGUILayout.Separator();

                    float volume = EditorGUILayout.Slider(new GUIContent("Volume", "Set global volume for this midi playing"), instance.MPTK_Volume, 0f, 1f);
                    if (instance.MPTK_Volume != volume)
                    {
                        instance.MPTK_Volume = volume;
                    }


                    EditorGUILayout.BeginHorizontal();
                    string tooltipDistance = "Playing is paused if distance between AudioListener and this component is greater than MaxDistance";
                    instance.MPTK_PauseOnDistance = EditorGUILayout.Toggle(new GUIContent("Pause With Distance", tooltipDistance), instance.MPTK_PauseOnDistance);
                    EditorGUILayout.LabelField(new GUIContent("Current:" + Math.Round(instance.distanceEditorModeOnly, 2), tooltipDistance));
                    EditorGUILayout.EndHorizontal();

                    float distance = EditorGUILayout.Slider(new GUIContent("Max Distance", tooltipDistance), instance.MPTK_MaxDistance, 0f, 500f);
                    if (instance.MPTK_MaxDistance != distance)
                    {
                        instance.MPTK_MaxDistance = distance;
                    }

                    EditorGUILayout.BeginHorizontal();
                    EditorGUILayout.PrefixLabel("Transpose");
                    instance.MPTK_Transpose = EditorGUILayout.IntSlider(instance.MPTK_Transpose, -24, 24);
                    EditorGUILayout.EndHorizontal();

                    EditorGUILayout.BeginHorizontal();
                    EditorGUILayout.PrefixLabel("Release Time (sec.)");
                    instance.MPTK_TimeToRelease = EditorGUILayout.Slider(instance.MPTK_TimeToRelease, 0.05f, 1f);
                    EditorGUILayout.EndHorizontal();

                    instance.MPTK_LogWaves = EditorGUILayout.Toggle(new GUIContent("Log Waves", "Log information about wave for each notes played"), instance.MPTK_LogWaves);
                }
                else
                {
                    EditorGUILayout.LabelField(new GUIContent("SoundFont: " + soundFontSelected, "Define SoundFont from the menu 'Tools/MPTK - SoundFont Setup' or alt-f"));
                    ToolsEditor.LoadMidiSet();
                    ToolsEditor.CheckMidiSet();
                }

                if (GUI.changed)
                {
                    EditorUtility.SetDirty(instance);
                }
            }
            catch (System.Exception ex)
            {
                MidiPlayerGlobal.ErrorDetail(ex);
            }
        }