Beispiel #1
0
        /// <summary>
        /// Play the midi file defined in MPTK_MidiName
        /// </summary>
        public virtual void MPTK_Play()
        {
            try
            {
                if (MidiPlayerGlobal.SoundFontLoaded)
                {
                    playPause = false;
                    if (!midiIsPlaying)
                    {
                        // Load description of available soundfont
                        if (MidiPlayerGlobal.ImSFCurrent != null && MidiPlayerGlobal.CurrentMidiSet != null && MidiPlayerGlobal.CurrentMidiSet.MidiFiles != null && MidiPlayerGlobal.CurrentMidiSet.MidiFiles.Count > 0)
                        {
                            //Debug.Log(MPTK_MidiName);
                            if (string.IsNullOrEmpty(MPTK_MidiName))
                            {
                                MPTK_MidiName = MidiPlayerGlobal.CurrentMidiSet.MidiFiles[0];
                            }
                            int selectedMidi = MidiPlayerGlobal.CurrentMidiSet.MidiFiles.FindIndex(s => s == MPTK_MidiName);
                            if (selectedMidi < 0)
                            {
                                Debug.LogWarning("MidiFilePlayer - MidiFile " + MPTK_MidiName + " not found. Try with the first in list.");
                                selectedMidi  = 0;
                                MPTK_MidiName = MidiPlayerGlobal.CurrentMidiSet.MidiFiles[0];
                            }

                            StartCoroutine(ThreadPlay());
                            //StartCoroutine(TestWithDelay());
                        }
                        else
                        {
                            Debug.LogWarning("MidiFilePlayer - no SoundFont or Midi set defined, go to Unity menu Tools to setup MPTK");
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
                MidiPlayerGlobal.ErrorDetail(ex);
            }
        }
Beispiel #2
0
        private IEnumerator TheadPlay(List <MPTKNote> notes)
        {
            if (notes != null && notes.Count > 0)
            {
                try
                {
                    if (MPTK_PauseOnDistance)
                    {
                        distanceEditorModeOnly = MidiPlayerGlobal.MPTK_DistanceToListener(this.transform);
                        if (distanceEditorModeOnly > AudioSourceTemplate.maxDistance)
                        {
                            notes.Clear();
                        }
                    }
                }
                catch (System.Exception ex)
                {
                    MidiPlayerGlobal.ErrorDetail(ex);
                }

                try
                {
                    List <MidiNote> midinotes = new List <MidiNote>();
                    foreach (MPTKNote note in notes)
                    {
                        midinotes.Add(note.ToMidiNote());
                    }
                    MPTK_PlayNotes(midinotes);
                    //Debug.Log("---------------- play count:" + notes.Count + " " + timeFromStartMS );
                }
                catch (System.Exception ex)
                {
                    MidiPlayerGlobal.ErrorDetail(ex);
                }
            }
            yield return(0);
        }
Beispiel #3
0
        public static void LoadCurrentSF()
        {
            // Load simplfied soundfont
            try
            {
                DateTime start = DateTime.Now;
                if (CurrentMidiSet == null)
                {
                    Debug.LogWarning("No SoundFont defined, go to Unity menu Tools to add a Soundfont");
                }
                else
                {
                    SoundFontInfo sfi = CurrentMidiSet.ActiveSounFontInfo;
                    if (sfi == null)
                    {
                        Debug.LogWarning("No SoundFont defined, go to Unity menu Tools to add a Soundfont");
                    }
                    else
                    {
                        // Path to the soundfonts directory for this SF, start from resource folder
                        string pathToImSF = Path.Combine(SoundfontsDB + "/", sfi.Name);
                        // Path to the soundfonts file for this SF
                        TextAsset sf = Resources.Load <TextAsset>(Path.Combine(pathToImSF + "/", sfi.Name));
                        if (sf == null)
                        {
                            Debug.LogWarning("No SoundFont found " + pathToImSF);
                        }
                        else
                        {
                            WavePath = Path.Combine(pathToImSF + "/", PathToWave);
                            // Load all presets defined in the XML sf
                            ImSFCurrent         = ImSoundFont.Load(sf.text);
                            timeToLoadSoundFont = DateTime.Now - start;
                            BuildPresetList();
                            BuildDrumList();
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
                MidiPlayerGlobal.ErrorDetail(ex);
            }

            if (ImSFCurrent == null)
            {
                Debug.LogWarning("SoundFont not loaded.");
                return;
            }

            // Load samples only in run mode
            if (Application.isPlaying)
            {
                try
                {
                    MPTK_CountWaveLoaded   = 0;
                    MPTK_CountPresetLoaded = 0;
                    DateTime start = DateTime.Now;
                    for (int ibank = 0; ibank < ImSFCurrent.Banks.Length; ibank++)
                    {
                        if (ImSFCurrent.Banks[ibank] != null)
                        {
                            for (int ipreset = 0; ipreset < ImSFCurrent.Banks[ibank].Presets.Length; ipreset++)
                            {
                                MPTK_CountPresetLoaded++;
                                if (ImSFCurrent.Banks[ibank].Presets[ipreset] != null)
                                {
                                    LoadSamples(ibank, ipreset);
                                }
                            }
                        }
                    }
                    timeToLoadWave = DateTime.Now - start;
                }
                catch (System.Exception ex)
                {
                    MidiPlayerGlobal.ErrorDetail(ex);
                }
            }
            if (OnEventPresetLoaded != null)
            {
                OnEventPresetLoaded.Invoke();
            }
        }
Beispiel #4
0
        /// <summary>
        /// Call by the first MidiPlayer awake
        /// </summary>
        //public static void Init()
        //{
        //    Instance.StartCoroutine(Instance.InitThread());
        //}

        /// <summary>
        /// Call by the first MidiPlayer awake
        /// </summary>
        private IEnumerator InitThread()
        {
            if (!Initialized)
            {
                //Debug.Log("MidiPlayerGlobal InitThread");
                SoundFontLoaded = false;
                Initialized     = true;
                ImSFCurrent     = null;

                try
                {
                    AudioListener = Component.FindObjectOfType <AudioListener>();
                    if (AudioListener == null)
                    {
                        Debug.LogWarning("No audio listener found. Add one and only one AudioListener component to your hierarchy.");
                        //return;
                    }
                }
                catch (System.Exception ex)
                {
                    MidiPlayerGlobal.ErrorDetail(ex);
                }

                try
                {
                    AudioListener[] listeners = Component.FindObjectsOfType <AudioListener>();
                    if (listeners != null && listeners.Length > 1)
                    {
                        Debug.LogWarning("More than one audio listener found. Some unexpected behaviors could happen.");
                    }
                }
                catch (System.Exception ex)
                {
                    MidiPlayerGlobal.ErrorDetail(ex);
                }

                try
                {
                    LoadMidiSetFromRsc();
                    DicAudioClip.Init();
                }
                catch (System.Exception ex)
                {
                    MidiPlayerGlobal.ErrorDetail(ex);
                }

                if (CurrentMidiSet == null)
                {
                    Debug.LogWarning("No Midi defined, go to menu 'Tools/MPTK - Midi File Setup' or alt-m");
                    yield return(0);
                }
                else if (CurrentMidiSet.ActiveSounFontInfo == null)
                {
                    Debug.LogWarning("No Active SoundFont found. Define SoundFont from the menu 'Tools/MPTK - SoundFont Setup' or alt-f");
                    yield return(0);
                }

                LoadCurrentSF();
                //Debug.Log("");

                if (ImSFCurrent != null)
                {
                    SoundFontLoaded = true;
                }
            }
        }
Beispiel #5
0
        /// <summary>
        /// Play one note - [New 1.7]
        /// </summary>
        /// <param name="note"></param>
        public void MPTK_PlayNote(MidiNote note)
        {
            try
            {
                // Search sample associated to the preset, midi note and velocity
                int selectedBank = note.Drum ? MidiPlayerGlobal.CurrentMidiSet.ActiveSounFontInfo.DrumKitBankNumber : selectedBank = MidiPlayerGlobal.CurrentMidiSet.ActiveSounFontInfo.DefaultBankNumber;
                int noteMidi     = note.Midi;
                if (!note.Drum)
                {
                    noteMidi += MPTK_Transpose;
                }

                //ImSample smpl = MidiPlayerGlobal.GetImSample(selectedBank, note.Patch, noteMidi, note.Velocity);
                //if (smpl != null)
                {
                    List <ImSample> samples = MidiPlayerGlobal.GetImMultiSample(selectedBank, note.Patch, noteMidi, note.Velocity);
                    //LogInfoSample(note, null, " Found " + samples.Count + " samples");
                    foreach (ImSample smpl in samples)
                    {
                        note.Pitch = Mathf.Pow(_ratioHalfTone, (float)(noteMidi - smpl.OriginalPitch + smpl.CoarseTune) + (float)smpl.FineTune / 100f);
                        // Load wave from audioclip
                        AudioClip clip = DicAudioClip.Get(smpl.WaveFile);
                        if (clip != null && clip.loadState == AudioDataLoadState.Loaded)
                        {
                            if (MPTK_LogWaves)
                            {
                                LogInfoSample(note, smpl);
                            }

                            AudioSource audioSelected = null;

                            // Search audioclip not playing with the same wave
                            try
                            {
                                foreach (AudioSource audio in audiosources)
                                {
                                    //Debug.Log(audio.isPlaying + " " + audio.clip.name + " " + clip.name);
                                    if (!audio.isPlaying && audio.clip.name == clip.name)
                                    {
                                        audioSelected = audio;
                                        break;
                                    }
                                }
                            }
                            catch (System.Exception ex)
                            {
                                MidiPlayerGlobal.ErrorDetail(ex);
                            }

                            if (audioSelected == null)
                            {
                                // No audiosource available, create a new audiosource
                                audioSelected = Instantiate <AudioSource>(AudioSourceTemplate);
                                audioSelected.Stop();
                                audioSelected.transform.position = AudioSourceTemplate.transform.position;
                                audioSelected.transform.SetParent(this.transform);
                                audiosources.Add(audioSelected);
                                // Assign sound to audioclip
                                audioSelected.clip = clip;
                            }

                            // Play note
                            StartCoroutine(PlayNote(audioSelected, note.Drum, smpl, note, timeToRelease));
                        }
                        else
                        {
                            if (MPTK_LogWaves)
                            {
                                LogInfoSample(note, null, smpl.WaveFile + "         ******** Clip not ready to play or not found ******");
                            }
                        }
                    }
                    //else
                    if (samples.Count == 0)
                    {
                        if (MPTK_LogWaves)
                        {
                            LogInfoSample(note, null, "               ********* Sample not found *********");
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
                MidiPlayerGlobal.ErrorDetail(ex);
            }
        }
Beispiel #6
0
        protected IEnumerator ThreadPlay(byte[] midibytestoplay = null)
        {
            midiIsPlaying  = true;
            stopMidiToPlay = false;
            newMidiToPlay  = false;
            bool first = true;

            //Debug.Log("Start play");
            try
            {
                miditoplay = new MidiLoad();

                // No midi byte array, try to load from MidiFilesDN from resource
                if (midibytestoplay == null || midibytestoplay.Length == 0)
                {
                    TextAsset mididata = Resources.Load <TextAsset>(Path.Combine(MidiPlayerGlobal.MidiFilesDB, MPTK_MidiName));
                    midibytestoplay = mididata.bytes;
                }

                miditoplay.KeepNoteOff = MPTK_KeepNoteOff;
                miditoplay.Load(midibytestoplay);
            }
            catch (System.Exception ex)
            {
                MidiPlayerGlobal.ErrorDetail(ex);
            }

            if (miditoplay != null)
            {
                yield return(StartCoroutine(MPTK_ClearAllSound(true)));

                try
                {
                    OnEventStartPlayMidi.Invoke();
                }
                catch (System.Exception ex)
                {
                    MidiPlayerGlobal.ErrorDetail(ex);
                }

                try
                {
                    miditoplay.ChangeSpeed(MPTK_Speed);
                    miditoplay.ChangeQuantization(MPTK_Quantization);
                }
                catch (System.Exception ex)
                {
                    MidiPlayerGlobal.ErrorDetail(ex);
                }

                lastTimePlay      = Time.realtimeSinceStartup;
                timeFromStartPlay = 0d;
                // Loop on each events midi
                do
                {
                    miditoplay.LogEvents         = MPTK_LogEvents;
                    miditoplay.EnableChangeTempo = MPTK_EnableChangeTempo;
                    miditoplay.EnablePanChange   = MPTK_EnablePanChange;

                    if (MPTK_PauseOnDistance)
                    {
                        distanceEditorModeOnly = MidiPlayerGlobal.MPTK_DistanceToListener(this.transform);
                        if (distanceEditorModeOnly > AudioSourceTemplate.maxDistance)
                        {
                            lastTimePlay = Time.realtimeSinceStartup;
                            yield return(new WaitForSeconds(0.2f));

                            continue;
                        }
                    }

                    if (playPause)
                    {
                        lastTimePlay = Time.realtimeSinceStartup;
                        yield return(new WaitForSeconds(0.2f));

                        if (miditoplay.EndMidiEvent || newMidiToPlay || stopMidiToPlay)
                        {
                            break;
                        }
                        if (timeToPauseMilliSeconde > -1f)
                        {
                            timeToPauseMilliSeconde -= 0.2f;
                            if (timeToPauseMilliSeconde <= 0f)
                            {
                                playPause = false;
                            }
                        }
                        continue;
                    }

                    if (!first)
                    {
                        timeFromStartPlay += (Time.realtimeSinceStartup - lastTimePlay) * 1000f;
                    }
                    else
                    {
                        timeFromStartPlay = 0d;
                        first             = false;
                    }
                    lastTimePlay = Time.realtimeSinceStartup;

                    //Debug.Log("---------------- " + timeFromStartPlay );
                    // Read midi events until this time
                    List <MidiNote> notes = miditoplay.ReadMidiEvents(timeFromStartPlay);

                    if (miditoplay.EndMidiEvent || newMidiToPlay || stopMidiToPlay)
                    {
                        break;
                    }

                    // Play notes read
                    if (notes != null && notes.Count > 0)
                    {
                        try
                        {
                            if (OnEventNotesMidi != null)
                            {
                                OnEventNotesMidi.Invoke(notes);
                            }
                        }
                        catch (System.Exception ex)
                        {
                            MidiPlayerGlobal.ErrorDetail(ex);
                        }

                        if (MPTK_DirectSendToPlayer)
                        {
                            MPTK_PlayNotes(notes);
                        }
                        //Debug.Log("---------------- play count:" + notes.Count + " " + timeFromStartMS );
                    }
                    if (Application.isEditor)
                    {
                        TimeSpan times = TimeSpan.FromMilliseconds(timeFromStartPlay);
                        playTimeEditorModeOnly = string.Format("{0:00}:{1:00}:{2:00}:{3:000}", times.Hours, times.Minutes, times.Seconds, times.Milliseconds);
                        durationEditorModeOnly = string.Format("{0:00}:{1:00}:{2:00}:{3:000}", MPTK_Duration.Hours, MPTK_Duration.Minutes, MPTK_Duration.Seconds, MPTK_Duration.Milliseconds);
                    }

                    yield return(new WaitForSeconds(delayMilliSeconde / 1000f));// 0.01f);
                }while (true);
            }

            midiIsPlaying = false;

            try
            {
                if (OnEventEndPlayMidi != null && !stopMidiToPlay && !newMidiToPlay)
                {
                    OnEventEndPlayMidi.Invoke();
                }

                if ((MPTK_Loop || newMidiToPlay) && !stopMidiToPlay)
                {
                    MPTK_Play();
                }
                //stopMidiToPlay = false;
            }
            catch (System.Exception ex)
            {
                MidiPlayerGlobal.ErrorDetail(ex);
            }
            //Debug.Log("Stop play");
        }