Ejemplo n.º 1
0
        /** Create a MidiTrack based on the Midi events.  Extract the NoteOn/NoteOff
         *  events to gather the list of MidiNotes.
         */
        public MidiTrack(List<MidiEvent> events, int tracknum)
        {
            this.tracknum = tracknum;
            notes = new List<MidiNote>(events.Count);
            instrument = 0;

            foreach (MidiEvent mevent in events) {
            if (mevent.EventFlag == MidiFile.EventNoteOn && mevent.Velocity > 0) {
                MidiNote note = new MidiNote(mevent.StartTime, mevent.Channel, mevent.Notenumber, 0);
                AddNote(note);
            }
            else if (mevent.EventFlag == MidiFile.EventNoteOn && mevent.Velocity == 0) {
                NoteOff(mevent.Channel, mevent.Notenumber, mevent.StartTime);
            }
            else if (mevent.EventFlag == MidiFile.EventNoteOff) {
                NoteOff(mevent.Channel, mevent.Notenumber, mevent.StartTime);
            }
            else if (mevent.EventFlag == MidiFile.EventProgramChange) {
                instrument = mevent.Instrument;
            }
            else if (mevent.Metaevent == MidiFile.MetaEventLyric) {
                if (lyrics == null) {
                    lyrics = new List<MidiEvent>();
                }
                lyrics.Add(mevent);
            }
            }
            if (notes.Count > 0 && notes[0].Channel == 9)  {
            instrument = 128;  /* Percussion */
            }
            int lyriccount = 0;
            if (lyrics != null) { lyriccount = lyrics.Count; }
        }
Ejemplo n.º 2
0
    private void ReadFile()
    {
        StreamReader sr = new StreamReader(Application.streamingAssetsPath + "\\" + filePath + ".miditext");
        string fileContents = sr.ReadToEnd();
        sr.Close();

        var lines = fileContents.Split("\n"[0]);
        foreach (string line in lines)
        {
            //milliseconds
            //on/off
            //channel
            //note
            //velocity

            string[] splitString = line.Split(" "[0]);
            splitString[2] = splitString[2].Substring(3);
            splitString[3] = splitString[3].Substring(2);
            splitString[4] = splitString[4].Substring(2);
            MidiNote tempM = new MidiNote(splitString);

            midiNotes.Add(tempM);

        }
    }
Ejemplo n.º 3
0
 public void NoteOff(MidiNote note, MidiOctave octave)
 {
     EnsureReady();
     Output.Send(new byte[] {
         MidiEvent.NoteOff, MapNote(note, octave), 0x7f
     }, 0, 3, 0);
 }
Ejemplo n.º 4
0
 /// <summary>
 /// Return note length as https://en.wikipedia.org/wiki/Note_value [New 1.9]
 /// </summary>
 /// <param name="note"></param>
 /// <returns></returns>
 public MidiNote.EnumLength NoteLength(MidiNote note)
 {
     if (miditoplay != null)
     {
         return(miditoplay.NoteLength(note));
     }
     return(MidiNote.EnumLength.Sixteenth);
 }
Ejemplo n.º 5
0
 void addNote(int key,int duration)
 {
     MidiNote note = new MidiNote(key,currentTime,duration,100);
     currentTime += duration;
     SheetNote sheetNote = createSheetNote(note);
     sheetNote.keyTrack = tracks[note.pitch];
     tracks[note.pitch].noteList.Add(sheetNote);
     noteList.Add(sheetNote);
 }
Ejemplo n.º 6
0
 public MidiNote(MidiNote other)
 {
     noteName        = other.noteName;
     noteOctave      = other.noteOctave;
     time            = other.time;
     noteLength      = other.noteLength;
     beatIndex       = other.beatIndex;
     beatLengthIndex = other.beatLengthIndex;
 }
Ejemplo n.º 7
0
 public SheetNote createSheetNote(MidiNote note)
 {
     SheetNote shownote = (Instantiate(SheetNotePrefab.gameObject,Vector3.zero,Quaternion.identity) as GameObject).GetComponent<SheetNote>();
     shownote.transform.parent = transform;
     shownote.GetComponent<RectTransform>().localPosition = new Vector3(keyTransforms[note.pitch].localPosition.x,0,0);
     shownote.transform.localScale = Vector3.one;
     shownote.gameObject.SetActive(false);
     shownote.midiNote = note;
     return shownote;
 }
Ejemplo n.º 8
0
        public void Highlight(ButtonName button, bool isNoteOn, byte velocity)
        {
            Visibility result = Convert.ToVisibility(isNoteOn);
            var        status = isNoteOn ? MIDIStatus.NoteOn : MIDIStatus.NoteOff;
            MidiNote   note   = MidiNote.None;

            if (button == ButtonName.Red)
            {
                this.RedVisibility = result;
                note = MidiNote.AcousticSnare;
            }
            else if (button == ButtonName.Yellow_Tom)
            {
                this.YellowTomVisibility = result;
                note = MidiNote.LowTom;
            }
            else if (button == ButtonName.Blue_Tom)
            {
                this.BlueTomVisibility = result;
                note = MidiNote.HighFloorTom;
            }
            else if (button == ButtonName.Green_Tom)
            {
                this.GreenTomVisibility = result;
                note = MidiNote.LowFloorTom;
            }
            else if (button == ButtonName.Yellow)
            {
                this.YellowCymbalVisibility = result;
                note = MidiNote.ClosedHiHat;
            }
            else if (button == ButtonName.Green)
            {
                this.GreenCymbalVisibility = result;
                note = MidiNote.CrashCymbal1;
            }
            else if (button == ButtonName.Blue)
            {
                this.BlueCymbalVisibility = result;
                note = MidiNote.RideCymbal2;
            }
            else if (button == ButtonName.Bass)
            {
                this.BassVisibility = result;
                note = MidiNote.BassDrum1;
            }

            if (note != MidiNote.None)
            {
                MidiModel.Send(new MidiShortMessage(status, 9, (byte)note, velocity, 0));
            }
        }
Ejemplo n.º 9
0
    private void ReadMidiFile(MidiFile midiFile, List <MidiNote> midiNotes)
    {
        if (midiFile.Tracks > 1)
        {
            Debug.LogWarning("Warning! Midi file has more than one track. Taking first track");
        }
        int totalMidiEvents = midiFile.Events[0].Count;

        for (int i = 0; i < totalMidiEvents; i++)
        {
            MidiEvent midiEvent = midiFile.Events[0][i];
            if (timeSignature is null)
            {
                try
                {
                    timeSignature = (TimeSignatureEvent)midiEvent;
                }
                catch (InvalidCastException e) when(e.Data != null)
                {
                }
            }
            if (!MidiEvent.IsNoteOff(midiEvent))
            {
                // Get the final tick of the song
                if (i == totalMidiEvents - 1)
                {
                    int eventTime = (int)midiEvent.AbsoluteTime;
                    if (eventTime > finalTick)
                    {
                        finalTick = eventTime;
                    }
                }
                // Ensure that the midievent is a note, and not metadata
                if (midiEvent.CommandCode.ToString() == "NoteOn")
                {
                    // Note length is retrieved from the next midiEvent's deltaTime
                    float noteLength = 0;

                    // Not at the end yet
                    if (i < totalMidiEvents)
                    {
                        MidiEvent nextMidievent = midiFile.Events[0][i + 1];
                        noteLength = ((float)nextMidievent.DeltaTime / ticksperQuarterNote);
                    }
                    Debug.Log(noteLength);
                    MidiNote note = GenerateMidiNote(midiEvent.AbsoluteTime, noteLength);
                    midiNotes.Add(note);
                }
            }
        }
    }
Ejemplo n.º 10
0
 /// <summary>
 /// Convert a MPTKNote to a Midi Note - [New 1.7]
 /// </summary>
 /// <returns></returns>
 public MidiNote ToMidiNote()
 {
     midinote = new MidiNote()
     {
         Midi     = Note <= 0 ? 0 : (Note > 127 ? 127 : Note),
         Delay    = Delay <= 0 ? 0f : (Delay > 1000f ? 1000f : Delay),
         Patch    = Drum ? 0 : Patch <= 0 ? 0 : (Patch > 127 ? 127 : Patch),
         Drum     = Drum,
         Pan      = Pan,
         Duration = Duration <= 0 ? 200f : (Duration > 100000f ? 200f : Duration),
         Velocity = Velocity,
     };
     return(midinote);
 }
Ejemplo n.º 11
0
        /// <summary>
        /// Draw all notes visible in the clip
        /// </summary>
        /// <param name="g"></param>
        /// <param name="clip"></param>
        private void DrawNotes(Graphics g, Rectangle clip)
        {
            int Y  = 0;
            int H  = 0;
            int PH = pnlCanvas.Height;

            // if one track
            if (track1 != null)
            {
                #region one track
                for (int i = 0; i < track1.Notes.Count; i++)
                {
                    MidiNote nnote = track1.Notes[i];
                    Y = (int)(PH - nnote.StartTime * yscale);
                    H = (int)(nnote.Duration * yscale);

                    // draw note if note ends after begining of clip and if note begins before end of clip
                    if (Y + H >= clip.Y && (Y - H) <= clip.Y + clip.Height)
                    {
                        MakeNoteRectangle(g, nnote.Number, nnote.StartTime, nnote.Duration, nnote.Channel);
                    }
                }
                #endregion
            }
            else
            {
                #region alltracks

                // if all tracks
                for (int trk = 0; trk < sequence1.tracks.Count; trk++)
                {
                    Track track = sequence1.tracks[trk];
                    for (int i = 0; i < track.Notes.Count; i++)
                    {
                        MidiNote nnote = track.Notes[i];
                        Y = (int)(PH - nnote.StartTime * yscale);
                        H = (int)(nnote.Duration * yscale);
                        // draw note if note ends before begining of clip and if note begins before end of clip
                        if (Y + H >= clip.Y && (Y - H) <= clip.Y + clip.Height)
                        {
                            MakeNoteRectangle(g, nnote.Number, nnote.StartTime, nnote.Duration, nnote.Channel);
                        }
                    }
                }
                #endregion
            }
        }
Ejemplo n.º 12
0
            public byte[] GetNextNote(int delta = 0)
            {
                List<byte> bytes = new List<byte>();

                if (noteList.Count > 0)
                {
                    MidiNote note = noteList[0];

                    bytes.AddRange(GetDeltaTime(delta));
                    bytes.Add((byte)(0x90 | mTrackNo)); //  発音
                    bytes.Add((byte)note.GetNote()); //  音程
                    bytes.Add((byte)note.GetVel()); //  ベロシティ

                    noteList.RemoveAt(0);
                }
                return bytes.ToArray();
            }
Ejemplo n.º 13
0
        private void LogInfoSample(MidiNote note, ImSample sample, string info = null)
        {
            //TimeSpan playtime = TimeSpan.Zero;
            //if (miditoplay != null) playtime = miditoplay.CurrentMidiTime();

            //string time = string.Format("[{0:00}:{1:00}:{2:00}:{3:000}]", playtime.Hours, playtime.Minutes, playtime.Seconds, playtime.Milliseconds);
            string time = "";

            if (sample != null)
#if DEBUGPITCHNOTE
            { Debug.Log(string.Format("{0} C:{1,2} P:{2,3:000} D:{3} Note:{4,3:000} OriginalPitch:{5} PitchCorrection:{6} FineTune:{7} CoarseTune:{8} Duration:{9,4} sec. Velocity:{10} Wave:{11}",
                                      time, note.Chanel, note.Patch, note.Drum, note.Midi,
                                      sample.OriginalPitch, sample.PitchCorrection, sample.FineTune, sample.CoarseTune, Math.Round(note.Duration / 1000d, 2), note.Velocity, sample.WaveFile)); }
#else
            { Debug.Log(string.Format("{0} C:{1,2} P:{2,3:000} D:{3} Note:{4,3:000} {5,-3} Duration:{6,4} sec. Velocity:{7} Pan:{8} Wave:{9}",
                                      time, note.Channel, note.Patch, note.Drum, note.Midi, HelperNoteLabel.LabelFromMidi(note.Midi),
                                      Math.Round(note.Duration / 1000d, 2), note.Velocity, sample.Pan, sample.WaveFile)); }
Ejemplo n.º 14
0
 public void TestNotesOverlap()
 {
     SheetMusic.SetNoteSize(false);
     KeySignature key = new KeySignature(0, 0);
     int quarter = 400;
     TimeSignature time = new TimeSignature(4, 4, quarter, 60000);
     int num1 = WhiteNote.BottomTreble.Number();
     int num2 = num1 + 1;
     MidiNote note1 = new MidiNote(0, 0, num1, quarter);
     MidiNote note2 = new MidiNote(0, 0, num2, quarter);
     List<MidiNote> notes = new List<MidiNote>(2);
     notes.Add(note1);
     notes.Add(note2);
     ChordSymbol chord = new ChordSymbol(notes, key, time, Clef.Treble, null);
     Assert.AreEqual(chord.ToString(),
                     "ChordSymbol clef=Treble start=0 end=400 width=25 hastwostems=False AccidSymbol accid=Sharp whitenote=F4 clef=Treble width=9 Note whitenote=F4 duration=Quarter leftside=True Note whitenote=F4 duration=Quarter leftside=True Stem duration=Quarter direction=1 top=F4 bottom=F4 end=E5 overlap=False side=2 width_to_pair=0 receiver_in_pair=False ");
 }
Ejemplo n.º 15
0
        public void SpawnNote(MidiNote note)
        {
            var noteSpawn    = GameObject.FindGameObjectWithTag(Const.Tags.NoteSpawn);
            var noteSpawnVec = noteSpawn.transform.position;

            var   vec = new Vector3(-6.38f, 2f, -1.05f);
            float timeOffset;

            GameObject newNote = Instantiate(GetRandomNoteSprite(), noteSpawnVec, Quaternion.Euler(90, 0, 0));

            note.Delay = (float)(Math.Abs(noteSpawnVec.x / noteSpeed * 1000)) - 100;

            var dist = /*noteEvent.Event.DeltaTime * */ (noteSpeed * Time.deltaTime);

            timeOffset = (float)(dist / (noteSpeed * Time.deltaTime));

            newNote.GetComponent <NoteBehavior>().InitNoteSpeed(noteSpeed, timeOffset);
        }
Ejemplo n.º 16
0
        private void sheetmusic_CurrentNoteChanged(MidiNote n)
        {
            if (busy)
            {
                return;
            }

            // Convert note number to letter
            string[] Scale    = { "A", "A#", "B", "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#" };
            string   NoteName = Scale[(n.Number + 3) % 12];

            upDownNoteValue.Value    = n.Number;
            lblNoteString.Text       = NoteName;
            lblTrackNumber.Text      = String.Format("Track #{0}", _tracknum);
            txtTime.Text             = sheetmusic.GetTimeInMeasure(n.StartTime).ToString();
            txtTicks.Text            = n.StartTime.ToString();
            txtDuration.Text         = n.Duration.ToString();
            upDownNoteVelocity.Value = n.Velocity;
        }
Ejemplo n.º 17
0
        /** Given the raw midi notes (the note number and duration in pulses),
         * calculate the following note data:
         * - The white key
         * - The accidental (if any)
         * - The note duration (half, quarter, eighth, etc)
         * - The side it should be drawn (left or side)
         * By default, notes are drawn on the left side.  However, if two notes
         * overlap (like A and B) you cannot draw the next note directly above it.
         * Instead you must shift one of the notes to the right.
         *
         * The KeySignature is used to determine the white key and accidental.
         * The TimeSignature is used to determine the duration.
         */

        private static NoteData[] CreateNoteData(List <MidiNote> midinotes, KeySignature key, TimeSignature time)
        {
            int len = midinotes.Count;

            NoteData[] notedata = new NoteData[len];

            for (int i = 0; i < len; i++)
            {
                MidiNote midi = midinotes[i];

                notedata[i] = new NoteData()
                {
                    number    = midi.Number,
                    leftside  = true,
                    whitenote = key.GetWhiteNote(midi.Number),
                    duration  = time.GetNoteDuration(midi.EndTime - midi.StartTime),
                    accid     = key.GetAccidental(midi.Number, midi.StartTime / time.Measure),
                };



                if (i > 0 && (notedata[i].whitenote.Dist(notedata[i - 1].whitenote) == 1))
                {
                    /* This note (notedata[i]) overlaps with the previous note.
                     * Change the side of this note.
                     */

                    if (notedata[i - 1].leftside)
                    {
                        notedata[i].leftside = false;
                    }
                    else
                    {
                        notedata[i].leftside = true;
                    }
                }
                else
                {
                    notedata[i].leftside = true;
                }
            }
            return(notedata);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Играет переданную ноту.
        /// </summary>
        /// <param name="note">Нота, которую необходимо проиграть.</param>
        public void PlayNote(MidiNote note)
        {
            Note         = note;
            noteVelocity = note.Velocity / 128f;
            var noteFrequency = (float)Utilities.MidiNoteToFrequency(note.NoteNo);

            oscA.Reset();
            oscB.Reset();
            filter.Reset();

            oscA.SetNoteFrequency(noteFrequency);
            oscB.SetNoteFrequency(noteFrequency);
            filter.SetNoteFrequency(noteFrequency);

            envA.TriggerAttack();
            envB.TriggerAttack();
            envFilter.TriggerAttack();

            IsActive = true;
        }
Ejemplo n.º 19
0
 public static void SendNote(MidiNote note)
 {
     if (outputDevice != null && outputDevice.IsOpen && !MidiInputCtrl.noteMute)
     {
         try
         {
             Pitch pitch = (Pitch)note.pitch;
             outputDevice.SendNoteOn(Channel.Channel1, pitch, 127);
             outputDevice.SendNoteOn(Channel.Channel1, pitch, 0);
             LogCtrl.Status("Send: " + note.note + " (" + note.pitch + ")");
         }
         catch (Exception e)
         {
             LogCtrl.Error("Couldn't send MIDI note!");
             LogCtrl.Error(e.ToString());
         }
     }
     else
     {
         LogCtrl.Warning("Send: " + note.note + " (" + note.pitch + ")");
     }
 }
Ejemplo n.º 20
0
        /// <summary>
        /// Add midi signal
        /// </summary>
        /// <param name="midiType">type of midi signal</param>
        private void AddMidi(MidiSignalTypes midiType, BaseMidiSignal midiSignal)
        {
            IRemovable midiVM = null;

            switch (midiType)
            {
            case MidiSignalTypes.MidiCC:
                if (midiSignal == null)
                {
                    midiSignal = new MidiCC();
                    m_conditionsBlock.MidiSignals.Add(midiSignal);
                }
                midiVM = new MidiCCViewModel((MidiCC)midiSignal);
                break;

            case MidiSignalTypes.MidiNote:
                if (midiSignal == null)
                {
                    midiSignal = new MidiNote();
                    m_conditionsBlock.MidiSignals.Add(midiSignal);
                }
                midiVM = new MidiNoteViewModel((MidiNote)midiSignal);
                break;
            }

            if (midiVM != null)
            {
                MidiSignals.Add(midiVM);

                //add remove delegate
                midiVM.DelegateToRemove = () =>
                {
                    m_conditionsBlock.MidiSignals.Remove(midiSignal);
                    MidiSignals.Remove(midiVM);
                };
            }
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Using SlNotes, select notes
        /// </summary>
        /// <param name="SlNotes"></param>
        public void RestoreSelectedNotes(List <MidiNote> SlNotes)
        {
            for (int i = 0; i < SlNotes.Count; i++)
            {
                MidiNote note = SlNotes[i];

                foreach (MusicSymbol s in symbols)
                {
                    // s is a chordsymbol
                    if (s.GetType() == typeof(ChordSymbol))
                    {
                        ChordSymbol C = (ChordSymbol)s;
                        foreach (MidiNote n in C.Notes)
                        {
                            if (note.Number == n.Number && note.StartTime == n.StartTime)
                            {
                                n.Selected = true;
                                s.Selected = true;
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Modify current Note
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPnlNoteOk_Click(object sender, EventArgs e)
        {
            if (busy)
            {
                return;
            }

            if (_lstmidinotes == null)
            {
                MidiNote n = new MidiNote(Convert.ToInt32(txtTicks.Text), sheetmusic.CurrentNote.midinote.Channel, Convert.ToInt32(upDownNoteValue.Value), Convert.ToInt32(txtDuration.Text), Convert.ToInt32(upDownNoteVelocity.Value), true);
                sheetmusic.ModifyCurrentNote(n, false);
                sheetmusic.Refresh();
            }
            else
            {
                // Update only velocity
                busy = true;

                sheetmusic.ModifyVelocitySelectedNotes(Convert.ToInt32(upDownNoteVelocity.Value));

                sheetmusic.Refresh();
                busy = false;
            }
        }
Ejemplo n.º 23
0
    public MidiNote[] GetNotes()
    {
        BuildTempoList();

        List <MidiNote> notes = new List <MidiNote>();

        double defaultTempo = 120;

        for (int n = 0; n < MidiFile.Tracks; n++)
        {
            foreach (MidiEvent midiEvent in MidiFile.Events[n])
            {
                try
                {
                    var tempoEvent = (NAudio.Midi.TempoEvent)midiEvent;
                    defaultTempo = tempoEvent.Tempo;
                }
                catch { }
            }
        }

        for (int n = 0; n < MidiFile.Tracks; n++)
        {
            foreach (MidiEvent midiEvent in MidiFile.Events[n])
            {
                if (MidiEvent.IsNoteOn(midiEvent))
                {
                    try
                    {
                        var      t_note = (NoteOnEvent)midiEvent;
                        MidiNote noteOn = new MidiNote();

                        noteOn.Note = t_note.NoteName;
                        //noteOn.Channel = t_note.Channel;
                        noteOn.Channel   = n;
                        noteOn.Velocity  = t_note.Velocity;
                        noteOn.StartTime = t_note.AbsoluteTime;

                        if (_tempoEvents.Count > 0)
                        {
                            try
                            {
                                noteOn.Tempo = MidiFile.DeltaTicksPerQuarterNote * _tempoEvents.Last(a => a.AbsoluteTime <= t_note.AbsoluteTime).BPM / 60;
                            }
                            catch (Exception e)
                            {
                                noteOn.Tempo = MidiFile.DeltaTicksPerQuarterNote * defaultTempo / 60;
                            }
                        }
                        else
                        {
                            noteOn.Tempo = MidiFile.DeltaTicksPerQuarterNote * defaultTempo / 60;
                        }

                        noteOn.Length = t_note.NoteLength / (float)noteOn.Tempo;

                        notes.Add(noteOn);
                    }
                    catch (Exception formatEx)
                    {
                        throw formatEx;
                    }
                }
            }
        }

        return(SortNotes(notes).ToArray());
    }
Ejemplo n.º 24
0
 /** Add a MidiNote to this track.  This is called for each NoteOn event */
 public void AddNote(MidiNote m)
 {
     notes.Add(m);
 }
Ejemplo n.º 25
0
 public void TestWholeDuration()
 {
     SheetMusic.SetNoteSize(false);
     KeySignature key = new KeySignature(0, 0);
     int quarter = 400;
     TimeSignature time = new TimeSignature(4, 4, quarter, 60000);
     int num1 = WhiteNote.BottomTreble.Number();
     MidiNote note1 = new MidiNote(0, 0, num1, quarter*4);
     List<MidiNote> notes = new List<MidiNote>(2);
     notes.Add(note1);
     ChordSymbol chord = new ChordSymbol(notes, key, time, Clef.Treble, null);
     Assert.AreEqual(chord.ToString(),
                     "ChordSymbol clef=Treble start=0 end=1600 width=16 hastwostems=False Note whitenote=F4 duration=Whole leftside=True ");
 }
Ejemplo n.º 26
0
    // Update is called once per frame
    void Update()
    {
        if (_isPlaying == true)
        {
            if (_audioDelayTime > 0f)
            {
                _audioDelayTime -= Time.deltaTime;
            }

            else
            {
                if (_audioStarted == false)
                {
                    _audioStarted = true;
                    if (audioSource != null)
                    {
                        audioSource.Play();
                    }
                }
            }

            if (_midiDelayTime > 0f)
            {
                _midiDelayTime -= Time.deltaTime;
            }
            else
            {
                _playTime += (Time.deltaTime * playSpeed);
                for (int i = 0; i < _tracks.Length; i++)
                {
                    int noteCount = _tracks[i].Notes.Count;
                    for (int j = _noteIndex[i]; j < noteCount; j++)
                    {
                        MidiNote note  = _tracks[i].Notes[j];
                        float    sTime = note.StartTime * _pulseTime;
                        float    eTime = note.EndTime * _pulseTime;

                        if (_playTime < sTime)
                        {
                            break;
                        }

                        // Midi Event Trigger Call
                        foreach (MidiEventTrigger trigger in _triggers)
                        {
                            trigger.NoteOn(_tracks[i].Instrument, note.Number);
                        }

                        if (_playTime > eTime)
                        {
                            _noteIndex[i] = j + 1;

                            // Midi Event Trigger Call
                            foreach (MidiEventTrigger trigger in _triggers)
                            {
                                trigger.NoteOff(_tracks[i].Instrument, note.Number);
                            }
                        }
                    }
                }
            }
        }
    }
Ejemplo n.º 27
0
 public async Task ReleaseNote(MidiNote note)
 {
     await Clients.All.SendAsync("NoteReleased", note);
 }
Ejemplo n.º 28
0
 bool SameChanelComparer(MidiNote a, MidiNote b)
 {
     return(a.Ch == b.Ch);
 }
Ejemplo n.º 29
0
 public void TestRoundDurations()
 {
     MidiTrack track = new MidiTrack(1);
     MidiNote note = new MidiNote(0, 0, 55, 45);
     track.AddNote(note);
     int[] starttimes = new int[] { 50, 90, 101, 123 };
     foreach (int start in starttimes) {
         note = new MidiNote(start, 0, 55, 1);
         track.AddNote(note);
     }
     List<MidiTrack> tracks = new List<MidiTrack>();
     tracks.Add(track);
     int quarternote = 40;
     MidiFile.RoundDurations(tracks, quarternote);
     Assert.AreEqual(track.Notes[0].Duration, 45);
     Assert.AreEqual(track.Notes[1].Duration, 40);
     Assert.AreEqual(track.Notes[2].Duration, 10);
     Assert.AreEqual(track.Notes[3].Duration, 20);
     Assert.AreEqual(track.Notes[4].Duration, 1);
 }
Ejemplo n.º 30
0
        private void method_3(Stream midiStream)
        {
            var midiFile = new BinaryReader(midiStream);

            ByteFiddler.smethod_3("MIDI", midiFile, "MThd");
            ByteFiddler.RotateLeft(midiFile.ReadUInt32());
            ByteFiddler.RotateRight(midiFile.ReadUInt16());
            int num = ByteFiddler.RotateRight(midiFile.ReadUInt16());

            method_1(ByteFiddler.RotateRight(midiFile.ReadUInt16()));
            MidiLineList.Clear();
            for (var i = 0; i < num; i++)
            {
                var midiLine = new MidiLine(method_0());
                MidiLineList.Add(midiLine);
                var list = new List <AbstractNoteClass>();
                ByteFiddler.smethod_3("MIDI", midiFile, "MTrk");
                var  num2     = ByteFiddler.RotateLeft(midiFile.ReadUInt32());
                var  position = midiFile.BaseStream.Position;
                var  num3     = 0;
                byte b        = 0;
                while (midiFile.BaseStream.Position < position + num2)
                {
                    var num4 = (int)method_4(midiFile);
                    AbstractNoteClass midiNote = null;
                    num3 += num4;
                    var b2 = midiFile.ReadByte();
                    if (b2 != 255)
                    {
                        byte int_;
                        if ((b2 & 128) == 128)
                        {
                            int_ = midiFile.ReadByte();
                            b    = b2;
                        }
                        else
                        {
                            int_ = b2;
                            b2   = b;
                        }
                        var b3 = (byte)(b2 >> 4);
                        switch (b3)
                        {
                        case 8:
                            midiNote = new MidiNote(num3, int_, midiFile.ReadByte(), false);
                            goto IL_298;

                        case 9:
                            midiNote = new MidiNote(num3, int_, midiFile.ReadByte(), true);
                            goto IL_298;

                        case 11:
                        case 12:
                        case 14:
                            goto IL_298;
                        }
                        throw new NotImplementedException(string.Format("Unhandled MIDI command: {0} at position {1}",
                                                                        b3.ToString("X"), midiFile.BaseStream.Position));
                    }
                    var b4    = midiFile.ReadByte();
                    var num5  = method_4(midiFile);
                    var array = midiFile.ReadBytes((int)num5);
                    var b5    = b4;
                    if (b5 <= 47)
                    {
                        switch (b5)
                        {
                        case 1:
                            midiNote = new ZzNote1(num3, ZzNote1.Enum37.Const0, Encoding.ASCII.GetString(array));
                            break;

                        case 2:
                            break;

                        case 3:
                        {
                            var text = Encoding.ASCII.GetString(array).ToUpper();
                            if (!string.IsNullOrEmpty(text))
                            {
                                midiLine.method_3(text);
                            }
                            break;
                        }

                        default:
                            if (b5 != 47)
                            {
                            }
                            break;
                        }
                    }
                    else if (b5 != 81)
                    {
                        if (b5 == 88)
                        {
                            if (num5 != 4L)
                            {
                                Class355.Interface150.imethod_1(string.Format(
                                                                    "Expected time signature event to have data length of 4, but found instead {0}",
                                                                    num5));
                            }
                            midiNote = new ZzNote338(num3, array[0], array[1], array[2], array[3]);
                        }
                    }
                    else
                    {
                        if (num5 != 3L)
                        {
                            Class355.Interface150.imethod_1(
                                string.Format("Expected tempo event to have data length of 3, but found instead {0}",
                                              num5));
                        }
                        var num6 = array[0] << 16;
                        num6    |= array[1] << 8;
                        num6    |= array[2];
                        midiNote = new BpmNote1(num3, num6);
                    }
IL_298:
                    if (midiNote != null)
                    {
                        list.Add(midiNote);
                    }
                }
                list.Sort(AbstractNoteClass.smethod_0);
                midiLine.method_1(list);
                midiFile.BaseStream.Seek(position + num2, SeekOrigin.Begin);
            }
        }
Ejemplo n.º 31
0
    public void TestSplitTrack()
    {
        MidiTrack track = new MidiTrack(1);
        int start, number;

        /* Create notes between 70 and 80 */
        for (int i = 0; i < 100; i++) {
            start = i * 10;
            number = 70 + (i % 10);
            MidiNote note = new MidiNote(start, 0, number, 10);
            track.AddNote(note);
        }

        /* Create notes between 65 and 75 */
        for (int i = 0; i < 100; i++) {
            start = i * 10 + 1;
            number = 65 + (i % 10);
            MidiNote note = new MidiNote(start, 0, number, 10);
            track.AddNote(note);
        }

        /* Create notes between 50 and 60 */
        for (int i = 0; i < 100; i++) {
            start = i * 10;
            number = 50 + (i % 10);
            MidiNote note = new MidiNote(start, 0, number, 10);
            track.AddNote(note);
        }

        /* Create notes between 55 and 65 */
        for (int i = 0; i < 100; i++) {
            start = i * 10 + 1;
            number = 55 + (i % 10);
            MidiNote note = new MidiNote(start, 0, number, 10);
            track.AddNote(note);
        }

        track.Notes.Sort( track.Notes[0] );
        List<MidiTrack> tracks = MidiFile.SplitTrack(track, 40);

        Assert.AreEqual(tracks[0].Notes.Count, 200);
        Assert.AreEqual(tracks[1].Notes.Count, 200);

        for (int i = 0; i < 100; i++) {
            MidiNote note1 = tracks[0].Notes[i*2];
            MidiNote note2 = tracks[0].Notes[i*2 + 1];
            Assert.AreEqual(note1.StartTime, i*10);
            Assert.AreEqual(note2.StartTime, i*10 + 1);
            Assert.AreEqual(note1.Number, 70 + (i % 10));
            Assert.AreEqual(note2.Number, 65 + (i % 10));
        }
        for (int i = 0; i < 100; i++) {
            MidiNote note1 = tracks[1].Notes[i*2];
            MidiNote note2 = tracks[1].Notes[i*2 + 1];
            Assert.AreEqual(note1.StartTime, i*10);
            Assert.AreEqual(note2.StartTime, i*10 + 1);
            Assert.AreEqual(note1.Number, 50 + (i % 10));
            Assert.AreEqual(note2.Number, 55 + (i % 10));
        }
    }
Ejemplo n.º 32
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);
            }
        }
Ejemplo n.º 33
0
        public async Task HitNote(MidiNote note)
        {
            Console.WriteLine($"{note.Note} at {note.Velocity}");

            await Clients.All.SendAsync("NoteHit", note);
        }
Ejemplo n.º 34
0
    public void TestCombineToSingleTrack()
    {
        List<MidiTrack> tracks = new List<MidiTrack>();
        int start, number;

        tracks.Add(new MidiTrack(1));
        for (int i = 1; i <= 99; i += 2) {
            start = i;
            number = 30 + (i % 10);
            MidiNote note = new MidiNote(start, 0, number, 10);
            tracks[0].AddNote(note);
        }
        tracks.Add(new MidiTrack(2));
        for (int i = 0; i <= 100; i += 2) {
            start = i;
            number = 50 + (i % 10);
            MidiNote note = new MidiNote(start, 0, number, 10);
            tracks[1].AddNote(note);
        }
        tracks.Add(new MidiTrack(3));
        for (int i = 0; i <= 100; i += 10) {
            start = i;
            number = 50 + (i % 10);
            MidiNote note = new MidiNote(start, 0, number, 20);
            tracks[2].AddNote(note);
        }

        MidiTrack track = MidiFile.CombineToSingleTrack(tracks);
        Assert.AreEqual(track.Notes.Count, 101);
        for (int i = 0; i <= 100; i++) {
            MidiNote note = track.Notes[i];
            Assert.AreEqual(note.StartTime, i);
            if (i % 2 == 0) {
                Assert.AreEqual(note.Number, 50 + (i % 10));
            }
            else {
                Assert.AreEqual(note.Number, 30 + (i % 10));
            }
            if (i % 10 == 0) {
                Assert.AreEqual(note.Duration, 20);
            }
            else {
                Assert.AreEqual(note.Duration, 10);
            }
        }
    }
Ejemplo n.º 35
0
        static byte MapNote(MidiNote note, MidiOctave octave)
        {
            int midinum = 12 * (int)octave + (int)note + 12;

            return((byte)midinum);
        }
Ejemplo n.º 36
0
 public void TestSixteenthDuration()
 {
     SheetMusic.SetNoteSize(false);
     KeySignature key = new KeySignature(0, 0);
     int quarter = 400;
     TimeSignature time = new TimeSignature(4, 4, quarter, 60000);
     int num1 = WhiteNote.BottomTreble.Number();
     MidiNote note1 = new MidiNote(0, 0, num1, quarter/4);
     List<MidiNote> notes = new List<MidiNote>(2);
     notes.Add(note1);
     ChordSymbol chord = new ChordSymbol(notes, key, time, Clef.Treble, null);
     Assert.AreEqual(chord.ToString(),
                     "ChordSymbol clef=Treble start=0 end=100 width=16 hastwostems=False Note whitenote=F4 duration=Sixteenth leftside=True Stem duration=Sixteenth direction=1 top=F4 bottom=F4 end=G5 overlap=False side=2 width_to_pair=0 receiver_in_pair=False ");
     Assert.AreEqual(chord.AboveStaff, SheetMusic.NoteHeight);
 }
Ejemplo n.º 37
0
        private static void InputDevice_NoteOn(NoteOnMessage msg)
        {
            Application.Current.Dispatcher.Invoke(new Action(() =>
            {
                if (msg.Velocity > 0)
                {
                    int pitch     = (int)msg.Pitch;
                    MidiNote note = MidiNote.getMidiNote(pitch);

                    if (note != null)
                    {
                        if (!noteMute)
                        {
                            if (pitch < 108)
                            {
                                for (int i = 0; i < CuelistCtrl.cues.Count; ++i)
                                {
                                    Cue cue = CuelistCtrl.cues[i];
                                    if (cue.trigger != null && cue.trigger.type == TriggerType.NOTE && cue.trigger.note.pitch == pitch)
                                    {
                                        if (Core.win.saveTriggerCheckbox.IsChecked && Core.win.cueTable.SelectedIndex != i)
                                        {
                                            LogCtrl.Error("In: " + note.note + " (" + note.pitch + ")");
                                        }
                                        else
                                        {
                                            LogCtrl.Success("In: " + note.note + " (" + note.pitch + ")");
                                            GoCtrl.Go(i);
                                        }
                                        return;
                                    }
                                }
                                LogCtrl.Status("In: " + note.note + " (" + note.pitch + ")");
                            }
                            else
                            {
                                LogCtrl.Status("In: " + note.note + " (" + note.pitch + ")");
                                if (pitch == 108)
                                {
                                    GoCtrl.GoNextCue();
                                }
                                else if (pitch == 109)
                                {
                                    GoCtrl.GoBack();
                                }
                                else if (pitch == 110)
                                {
                                    CuelistCtrl.SelectPrevCue();
                                }
                                else if (pitch == 111)
                                {
                                    CuelistCtrl.SelectNextCue();
                                }
                                else if (pitch >= 112 && pitch <= 121)
                                {
                                    ScriptlistCtrl.ExecuteScript(note.pitch - 111);
                                }
                            }
                        }
                        else
                        {
                            LogCtrl.Warning("In: " + note.note + " (" + note.pitch + ")");
                        }
                    }
                }
            }));
        }
Ejemplo n.º 38
0
        private void method_3(int instrumentType, int int1, MidiNote midiNote, int int2)
        {
            NoteEventInterpreter noteEvenInterpreter = null;

            switch (midiNote.GetDifficulty())
            {
            case Difficulty.Easy:
                switch (instrumentType)
                {
                case 0:
                    noteEvenInterpreter = _easySingle;
                    break;

                case 1:
                    noteEvenInterpreter = _easyDoubleGuitar;
                    break;

                case 3:
                    noteEvenInterpreter = _easyDoubleBass;
                    break;
                }
                break;

            case Difficulty.Medium:
                switch (instrumentType)
                {
                case 0:
                    noteEvenInterpreter = _mediumSingle;
                    break;

                case 1:
                    noteEvenInterpreter = _mediumDoubleGuitar;
                    break;

                case 3:
                    noteEvenInterpreter = _mediumDoubleBass;
                    break;
                }
                break;

            case Difficulty.Hard:
                switch (instrumentType)
                {
                case 0:
                    noteEvenInterpreter = _hardSingle;
                    break;

                case 1:
                    noteEvenInterpreter = _hardDoubleGuitar;
                    break;

                case 3:
                    noteEvenInterpreter = _hardDoubleBass;
                    break;
                }
                break;

            case Difficulty.Expert:
                switch (instrumentType)
                {
                case 0:
                    noteEvenInterpreter = _expertSingle;
                    break;

                case 1:
                    noteEvenInterpreter = _expertDoubleGuitar;
                    break;

                case 3:
                    noteEvenInterpreter = _expertDoubleBass;
                    break;
                }
                break;

            default:
                if (!_bool3 && midiNote.method_2() == MidiNoteMask.StarPower)
                {
                    _bool3 = true;
                    _expertSingle.Class2281.Clear();
                    _hardSingle.Class2281.Clear();
                    _mediumSingle.Class2281.Clear();
                    _easySingle.Class2281.Clear();
                }
                else if (!_bool3)
                {
                    return;
                }
                break;
            }
            if (midiNote.method_3() != Fret.Invalid)
            {
                if (noteEvenInterpreter.NoteList.method_4(int1))
                {
                    noteEvenInterpreter.NoteList[int1].NoteValues[(int)midiNote.method_3()] = true;
                    return;
                }
                var array = new bool[32];
                array[(int)midiNote.method_3()] = true;
                noteEvenInterpreter.NoteList.Add(int1, new NotesAtOffset(array, int2));
            }
            else
            {
                if (midiNote.method_2() == MidiNoteMask.StarPower && !_expertSingle.Class2281.ContainsKey(int1))
                {
                    _expertSingle.Class2281.Add(int1, int2);
                    _hardSingle.Class2281.Add(int1, int2);
                    _mediumSingle.Class2281.Add(int1, int2);
                    _easySingle.Class2281.Add(int1, int2);
                    return;
                }
                if (midiNote.method_2() == MidiNoteMask.Unk7 && !noteEvenInterpreter.Class2281.ContainsKey(int1) &&
                    !_bool3)
                {
                    noteEvenInterpreter.Class2281.Add(int1, int2);
                    return;
                }
                if (midiNote.method_2() == MidiNoteMask.Unk9 && !noteEvenInterpreter.Class2282.ContainsKey(int1))
                {
                    noteEvenInterpreter.Class2282.Add(int1, int2);
                    return;
                }
                if (midiNote.method_2() == MidiNoteMask.Unk10 && !noteEvenInterpreter.Class2283.ContainsKey(int1))
                {
                    noteEvenInterpreter.Class2283.Add(int1, int2);
                }
            }
        }
Ejemplo n.º 39
0
 public void TestAllTreble()
 {
     List<MidiNote> notes = new List<MidiNote>();
     for (int i = 0; i < 100; i++) {
         int num = middleC + (i % 5);
         MidiNote note = new MidiNote(i*10, 0, num, 5);
         notes.Add(note);
     }
     ClefMeasures clefs = new ClefMeasures(notes, 40);
     for (int i = 0; i < 100; i++) {
         Clef clef = clefs.GetClef(10 * i);
         Assert.AreEqual(clef, Clef.Treble);
     }
 }
Ejemplo n.º 40
0
 public void TestStemUpBass()
 {
     SheetMusic.SetNoteSize(false);
     KeySignature key = new KeySignature(0, 0);
     int quarter = 400;
     TimeSignature time = new TimeSignature(4, 4, quarter, 60000);
     int num1 = WhiteNote.BottomBass.Number();
     int num2 = num1 + 2;
     MidiNote note1 = new MidiNote(0, 0, num1, quarter);
     MidiNote note2 = new MidiNote(0, 0, num2, quarter);
     List<MidiNote> notes = new List<MidiNote>(2);
     notes.Add(note1);
     notes.Add(note2);
     ChordSymbol chord = new ChordSymbol(notes, key, time, Clef.Bass, null);
     Assert.AreEqual(chord.ToString(),
                     "ChordSymbol clef=Bass start=0 end=400 width=16 hastwostems=False Note whitenote=A3 duration=Quarter leftside=True Note whitenote=B3 duration=Quarter leftside=False Stem duration=Quarter direction=1 top=B3 bottom=A3 end=A4 overlap=True side=2 width_to_pair=0 receiver_in_pair=False ");
 }
Ejemplo n.º 41
0
        /// <summary>
        /// Play one note with this AudioSource
        /// </summary>
        /// <param name="audio">AudioSource</param>
        /// <param name="loop">Sound with loop</param>
        /// <param name="note"></param>
        /// <returns></returns>
        protected IEnumerator PlayNote(AudioSource audio, bool drum, ImSample sample, MidiNote note, float vTransitionTime)
        {
            if (note.Delay > 0f)
            {
                float endDelay = Time.realtimeSinceStartup + note.Delay / 1000f;
                while (Time.realtimeSinceStartup < endDelay && note.Delay > 0f)
                {
                    yield return(new WaitForSeconds(0.01f));
                }
            }

            try
            {
                audio.pitch = note.Pitch;
                if (drum)
                {
                    audio.loop = false;
                }
                else
                {
                    audio.loop = sample.IsLoop;
                }
                // Attenuation removed from current version
                //audio.volume = Mathf.Lerp(0f, 1f, note.Velocity * sample.Attenuation / 127f) * MPTK_Volume;
                audio.volume = Mathf.Lerp(0f, 1f, note.Velocity / 127f) * MPTK_Volume;

                // Pan from the SoundFont
                if (MidiPlayerGlobal.CurrentMidiSet.ActiveSounFontInfo.Panoramic)
                {
                    audio.panStereo = Mathf.Lerp(-1f, 1f, (sample.Pan + 500) / 1000f);
                }
                else
                {
                    audio.panStereo = 0f;
                }

                // Pan from the midi file or from a midi generated event
                if (note.Pan >= 0)
                {
                    audio.panStereo = Mathf.Lerp(-1f, 1f, note.Pan / 127f);
                }
                //Debug.Log(string.Format("   Pan  - note:{0,3} sample:{1,3} --> audio pan:{2,3}" , note.Pan , sample.Pan,Math.Round( audio.panStereo,2)));
                //Debug.Log(string.Format("   Vel  - note:{0,3} sample:{1,3} --> audio vel:{2,3}", note.Velocity , Math.Round(sample.Attenuation, 2), Math.Round(audio.volume, 2)));
                //Debug.Log(string.Format("   Loop - drum:{0} sample:{1}     --> audio loop:{2}" , drum , sample.IsLoop , audio.loop));

                audio.Play();
            }
            catch (Exception)
            {
            }

            // Attack & Decay taken in account by the wave, for drum (loop=false) play the wave one shot (no duration)
            if (audio.loop)
            {
                // Sustain phase until key release, constant amplitude
                float end = Time.realtimeSinceStartup + (float)(note.Duration / 1000d);
                while (note.Duration > 0f)
                {
                    try
                    {
                        if (Time.realtimeSinceStartup >= end || !audio.isPlaying)
                        {
                            break;
                        }
                    }
                    catch (Exception)
                    {
                    }
                    yield return(new WaitForSeconds(0.01f));
                }
                //Debug.Log("stop " + sample.WaveFile + " " + note.Duration);
                // Release phase
                if (vTransitionTime > 0f)
                {
                    float dtime  = 0f;
                    float volume = 0;

                    try
                    {
                        volume = audio.volume;
                        end    = Time.realtimeSinceStartup + vTransitionTime;
                    }
                    catch (Exception)
                    {
                    }

                    do
                    {
                        dtime = end - Time.realtimeSinceStartup;
                        try
                        {
                            audio.volume = Mathf.Lerp(0f, volume, dtime / vTransitionTime);
                            if (dtime < 0f || !audio.isPlaying)
                            {
                                break;
                            }
                        }
                        catch (Exception)
                        {
                            break;
                        }
                        yield return(new WaitForSeconds(0.01f));
                    }while (true);
                }

                try
                {
                    audio.Stop();
                }
                catch (Exception)
                {
                }
            }
            //else
            //{
            //    // play with no loop (drum)
            //    while (audio.isPlaying)
            //    {
            //        yield return new WaitForSeconds(0.01f);
            //    }
            //}
        }
Ejemplo n.º 42
0
 public void TestMainClefTreble()
 {
     List<MidiNote> notes = new List<MidiNote>();
     for (int i = 0; i < 100; i++) {
         int num = F4 + (i % 20);
         MidiNote note = new MidiNote(i*10, 0, num, 5);
         notes.Add(note);
     }
     for (int i = 100; i < 200; i++) {
         int num = G3 - (i % 2);
         MidiNote note = new MidiNote(i*10, 0, num, 5);
         notes.Add(note);
     }
     for (int i = 200; i < 300; i++) {
         int num = middleC - (i % 2);
         MidiNote note = new MidiNote(i*10, 0, num, 5);
         notes.Add(note);
     }
     ClefMeasures clefs = new ClefMeasures(notes, 50);
     for (int i = 0; i < 100; i++) {
         Clef clef = clefs.GetClef(i*10);
         Assert.AreEqual(clef, Clef.Treble);
     }
     for (int i = 100; i < 200; i++) {
         Clef clef = clefs.GetClef(i*10);
         Assert.AreEqual(clef, Clef.Bass);
     }
     for (int i = 200; i < 300; i++) {
         Clef clef = clefs.GetClef(i*10);
         /* Even though the average note is below middle C,
          * the main clef is treble.
          */
         Assert.AreEqual(clef, Clef.Treble);
     }
 }
Ejemplo n.º 43
0
        public void Highlight(ButtonName button, bool isNoteOn, byte velocity)
        {
            Visibility result = PsMidiProfiler.Helpers.Convert.ToVisibility(isNoteOn);
            var        status = isNoteOn ? MIDIStatus.NoteOn : MIDIStatus.NoteOff;
            MidiNote   note   = MidiNote.None;

            if (button == ButtonName.Red)
            {
                this.RedVisibility = result;
                note = MidiNote.AcousticSnare;
            }
            else if (button == ButtonName.Yellow_Tom)
            {
                this.YellowTomVisibility = result;
                note = MidiNote.LowTom;
            }
            else if (button == ButtonName.Blue)
            {
                this.BlueVisibility = result;
                note = MidiNote.RideCymbal2;
            }
            else if (button == ButtonName.Blue_Tom)
            {
                this.BlueTomVisibility = result;
                note = MidiNote.HighFloorTom;
            }
            else if (button == ButtonName.Green)
            {
                this.GreenVisibility = result;
                note = MidiNote.CrashCymbal1;
            }
            else if (button == ButtonName.Green_Tom)
            {
                this.GreenTomVisibility = result;
                note = MidiNote.LowFloorTom;
            }
            else if (button == ButtonName.Bass)
            {
                this.BassVisibility = result;
                note = MidiNote.BassDrum1;
            }
            else if (button == ButtonName.Yellow)
            {
                var hihatState = Helpers.Convert.ToHiHatState(this.HiHatPedalVelocity);
                switch (hihatState)
                {
                case HiHatState.Closed:
                    this.YellowClosedVisibility = result;
                    note = MidiNote.ClosedHiHat;
                    break;

                case HiHatState.HalfClosed:
                    this.YellowSizzleVisibility = result;
                    note = MidiNote.RideCymbal1;
                    break;

                case HiHatState.Opened:
                    this.YellowOpenVisibility = result;
                    note = MidiNote.OpenHiHat;
                    break;

                default:
                    throw new NotImplementedException("Not implemented HiHatState: " + hihatState);
                }
            }

            if (note != MidiNote.None)
            {
                MidiModel.Send(new MidiShortMessage(status, 9, (byte)note, velocity, 0));
            }
        }
Ejemplo n.º 44
0
 public NoteOnEvent(long absoluteTime, int channel, MidiNote noteNumber, int velocity, int duration)
     : base(absoluteTime, channel, MidiCommandCode.NoteOn, (int)noteNumber, velocity)
 {
     this.OffEvent = new NoteEvent(absoluteTime, channel, MidiCommandCode.NoteOff, (int)noteNumber, 0);
     NoteLength    = duration;
 }