Exemplo n.º 1
0
        private static void TestInsert()
        {
            Track track = new Track();
            int midiEventCount = 2000;
            int positionMax = 32000;
            int endOfTrackOffset = 1000;
            int length = 0;
            int position = 0;
            ChannelMessage message = new ChannelMessage(ChannelCommand.NoteOff, 0, 60, 0);
            Random r = new Random();

            for(int i = 0; i < midiEventCount; i++)
            {
                position = r.Next(positionMax);

                if(position > length)
                {
                    length = position;
                }

                track.Insert(position, message);
            }

            track.EndOfTrackOffset = endOfTrackOffset;

            length += track.EndOfTrackOffset;

            Debug.Assert(track.Count == midiEventCount + 1);
            Debug.Assert(track.Length == length);
        }
Exemplo n.º 2
0
        private static void TestRemoveAt()
        {
            Track a = new Track();
            ChannelMessage message = new ChannelMessage(ChannelCommand.NoteOff, 0, 60, 0);

            a.Insert(0, message);
            a.Insert(10, message);
            a.Insert(20, message);
            a.Insert(30, message);
            a.Insert(40, message);

            int count = a.Count;

            a.RemoveAt(0);

            Debug.Assert(a.Count == count - 1);

            a.RemoveAt(a.Count - 2);

            Debug.Assert(a.Count == count - 2);
            Debug.Assert(a.GetMidiEvent(0).AbsoluteTicks == 10);
            Debug.Assert(a.GetMidiEvent(a.Count - 2).AbsoluteTicks == 30);

            a.RemoveAt(0);
            a.RemoveAt(0);
            a.RemoveAt(0);

            Debug.Assert(a.Count == 1);
        }
        public void Process(ChannelMessage message)
        {
            switch(message.Command)
            {
                case ChannelCommand.Controller:
                    controllerMessages[message.MidiChannel, message.Data1] = message;
                    break;

                case ChannelCommand.ChannelPressure:
                    channelPressureMessages[message.MidiChannel] = message;
                    break;

                case ChannelCommand.PitchWheel:
                    pitchBendMessages[message.MidiChannel] = message;
                    break;

                case ChannelCommand.PolyPressure:
                    polyPressureMessages[message.MidiChannel] = message;
                    break;

                case ChannelCommand.ProgramChange:
                    programChangeMessages[message.MidiChannel] = message;
                    break;
            }
        }
        public override void SetData(ChannelMessage midiChannelMessage)
        {
            if (midiChannelMessage.Command != channelCommand ) return;
            if (midiChannelMessage.MidiChannel != midiChannel) return;
            if (midiChannelMessage.Data1 != data1) return;

            Value = midiChannelMessage.Data2;
        }
Exemplo n.º 5
0
        public void Process(ChannelMessage message)
        {
            switch(message.Command)
            {
                case ChannelCommand.NoteOn:
                    if(message.Data2 > 0)
                    {
                        noteOnMessage[message.MidiChannel, message.Data1] = message;
                    }
                    else
                    {
                        noteOnMessage[message.MidiChannel, message.Data1] = null;
                    }
                    break;

                case ChannelCommand.NoteOff:
                    noteOnMessage[message.MidiChannel, message.Data1] = null;
                    break;

                case ChannelCommand.Controller:
                    switch(message.Data1)
                    {
                        case (int)ControllerType.HoldPedal1:
                            if(message.Data2 > 63)
                            {
                                holdPedal1Message[message.MidiChannel] = true;
                            }
                            else
                            {
                                holdPedal1Message[message.MidiChannel] = false;
                            }
                            break;

                        case (int)ControllerType.HoldPedal2:
                            if(message.Data2 > 63)
                            {
                                holdPedal2Message[message.MidiChannel] = true;
                            }
                            else
                            {
                                holdPedal2Message[message.MidiChannel] = false;
                            }
                            break;

                        case (int)ControllerType.SustenutoPedal:
                            if(message.Data2 > 63)
                            {
                                sustenutoMessage[message.MidiChannel] = true;
                            }
                            else
                            {
                                sustenutoMessage[message.MidiChannel] = false;
                            }
                            break;
                    }
                    break;
            }
        }
Exemplo n.º 6
0
    public static void appendFingeringToMidiFile(Midi.Sequence file, Fingering[] fingerings)
    {
        if (file.Count == 0)
        {
            Debug.LogWarning("MIDI no track found.");
            return;
        }

        var FingerMap = new Dictionary <int, Dictionary <int, Finger> >();

        foreach (var fingering in fingerings)
        {
            if (fingering.markers == null)
            {
                Debug.LogWarning("fingering markers is null.");
                continue;
            }

            foreach (var marker in fingering.markers)
            {
                if (!FingerMap.ContainsKey(marker.tick))
                {
                    FingerMap[marker.tick] = new Dictionary <int, Finger>();
                }

                FingerMap[marker.tick][marker.pitch] = marker.finger;
                //Debug.LogFormat("marker: {0}, {1}, {2}", marker.tick, marker.pitch, marker.finger);
            }
        }

        clearFingeringInMidiFile(file);

        foreach (Midi.Track track in file)
        {
            foreach (Midi.MidiEvent e in track.Iterator())
            {
                if (e.MidiMessage.MessageType == Midi.MessageType.Channel)
                {
                    Midi.ChannelMessage cm = e.MidiMessage as Midi.ChannelMessage;
                    if (cm.Command == Midi.ChannelCommand.NoteOn)
                    {
                        if (FingerMap.ContainsKey(e.AbsoluteTicks) && FingerMap[e.AbsoluteTicks].ContainsKey(cm.Data1))
                        {
                            Finger f = FingerMap[e.AbsoluteTicks][cm.Data1];

                            string marker = string.Format("finger:{0}|{1}", cm.Data1, (int)f);

                            track.Insert(e.AbsoluteTicks, new Midi.MetaMessage(Midi.MetaType.Marker, Encoding.Default.GetBytes(marker)));
                        }
                    }
                }
            }
        }

        file[0].Insert(0, new Midi.MetaMessage(Midi.MetaType.Text, Encoding.Default.GetBytes(MidiSignatureText)));
    }
Exemplo n.º 7
0
        public override void SetData(ChannelMessage midiChannelMessage)
        {
            if (midiChannelMessage.Command == ChannelCommand.NoteOff || midiChannelMessage.Command == ChannelCommand.NoteOn)
            {
                if (midiChannelMessage.MidiChannel != midiChannel) return;
                if (midiChannelMessage.Data1 != data1) return;

                
                Velocity = (midiChannelMessage.Command == ChannelCommand.NoteOff ) ? 0 : midiChannelMessage.Data2;
                Pressed = (midiChannelMessage.Command == ChannelCommand.NoteOff) ? false :  midiChannelMessage.Data2 > 0;
            }
        }
Exemplo n.º 8
0
 public void Send(ChannelMessage message)
 {
     if (message.Command == ChannelCommand.NoteOn &&
         message.Data1 >= LowNoteID && message.Data1 <= HighNoteID)
     {
         if (message.Data2 > 0)
         {
             string sbName = "";
             switch (message.Data1)
             {
                 case (int)DrumInstrument.AcousticSnare: //38,
                 case (int)DrumInstrument.ElectricSnare: //40,
                     sbName = "sbSnareDrum";
                     break;
                 case (int)DrumInstrument.LowFloorTom: //41,
                 case (int)DrumInstrument.HighFloorTom: //43,
                     sbName = "sbFloorTom";
                     break;
                 case (int)DrumInstrument.LowTom: //45,
                 case (int)DrumInstrument.LowMidTom: //47,
                     sbName = "sbTom1";
                     break;
                 case (int)DrumInstrument.HiMidtom: //48,
                 case (int)DrumInstrument.HighTom: //50,
                     sbName = "sbTom2";
                     break;
                 case (int)DrumInstrument.AcousticBassDrum: //35,
                 case (int)DrumInstrument.BassDrum: //36,
                     sbName = "sbBassDrum";
                     break;
                 case (int)DrumInstrument.ClosedHiHat: //42,
                 case (int)DrumInstrument.PedalHiHat: //44,
                 case (int)DrumInstrument.OpenHiHat: //46,
                     sbName = "sbHiHat";
                     break;
                 case (int)DrumInstrument.CrashCymbal: //49,
                 case (int)DrumInstrument.RideCymbal: //51
                     sbName = "sbRideCymbal";
                     break;
             }
             if (!string.IsNullOrEmpty(sbName))
             {
                 Storyboard sb = (Storyboard)FindResource(sbName);
                 sb.Stop();
                 sb.Begin();
             }
         }
     }
 }
Exemplo n.º 9
0
        public void Send(ChannelMessage message)
        {
            int LowNoteID = 0;
            int HighNoteID = 87;

            Byte b ;
            if (message.Command == ChannelCommand.NoteOn &&
                message.Data1 >= LowNoteID && message.Data1 <= HighNoteID)
            {
                b = (byte) (message.Data1 -21) ;

                    KeyDown(b);

            }
            else if (message.Command == ChannelCommand.NoteOff &&
                message.Data1 >= LowNoteID && message.Data1 <= HighNoteID)
            {
                b = (byte) (message.Data1 - 21);
                KeyUp(b);
            }
        }
Exemplo n.º 10
0
        public static PianoKeyStrokeEventArgs ConvertChannelMessageToKeyStrokeEventArgs(ChannelMessage channelMessage)
        {
            var pksea = new PianoKeyStrokeEventArgs();

            //If the key stroke is neither a press or a release, return a null object
            switch (channelMessage.Command)
            {
                case ChannelCommand.NoteOn:
                    pksea.keyStrokeType = KeyStrokeType.KeyPress;
                    break;
                case ChannelCommand.NoteOff:
                    pksea.keyStrokeType = KeyStrokeType.KeyRelease;
                    break;
                default: return null;
            }

            pksea.midiKeyId = channelMessage.Data1;
            pksea.KeyVelocity = channelMessage.Data2;

            //Velocity 0 is effectively a key release
            if (pksea.KeyVelocity == 0) pksea.keyStrokeType = KeyStrokeType.KeyRelease;

            return pksea;
        }
        /// <summary>
        /// Builds a ChannelMessageEventArgs.
        /// </summary>
        public void Build()
        {
            result = (ChannelMessage)messageCache[message];

            // If the message does not exist.
            if(result == null)
            {
                result = new ChannelMessage(message);

                // Add message to cache.
                messageCache.Add(message, result);
            }
        }
 /// <summary>
 /// Initializes the ChannelMessageBuilder with the specified 
 /// ChannelMessageEventArgs.
 /// </summary>
 /// <param name="message">
 /// The ChannelMessageEventArgs to use for initializing the ChannelMessageBuilder.
 /// </param>
 public void Initialize(ChannelMessage message)
 {
     this.message = message.Message;
 }
Exemplo n.º 13
0
       /* public override bool Equals(Object obj)
        {
            var midiInputEvent = obj as IMidiEventListener;
            if (midiInputEvent == null)
            {
                return false;
            }

            return  Command == midiInputEvent.Command &&
                    MidiChannel == midiInputEvent.MidiChannel &&
                    Data1 == midiInputEvent.Data1;
        }
*/
        public abstract void SetData(ChannelMessage midiChannelMessage);
Exemplo n.º 14
0
 /// <summary>
 /// Initializes the ChannelMessageBuilder with the specified
 /// ChannelMessageEventArgs.
 /// </summary>
 /// <param name="message">
 /// The ChannelMessageEventArgs to use for initializing the ChannelMessageBuilder.
 /// </param>
 public void Initialize(ChannelMessage message)
 {
     this.message = message.Message;
 }
Exemplo n.º 15
0
        public override void Send(ChannelMessage message)
        {
            #region Require

            if(IsDisposed)
            {
                throw new ObjectDisposedException(this.GetType().Name);
            }

            #endregion

            lock(lockObject)
            {
                // If running status is enabled.
                if(runningStatusEnabled)
                {
                    // If the message's status value matches the running status.
                    if(message.Status == runningStatus)
                    {
                        // Send only the two data bytes without the status byte.
                        Send(message.Message >> 8);
                    }
                    // Else the message's status value does not match the running
                    // status.
                    else
                    {
                        // Send complete message with status byte.
                        Send(message.Message);

                        // Update running status.
                        runningStatus = message.Status;
                    }
                }
                // Else running status has not been enabled.
                else
                {
                    Send(message.Message);
                }
            }
        }
 public ChannelMessageBuilder Initialize(ChannelMessage message)
 {
     this.message = message.Message;
     return this;
 }
Exemplo n.º 17
0
        /// <summary>
        /// Evaluate a received midi message and take the appropriate action.
        /// </summary>
        private void CheckReceivedMessage(ChannelMessage channelMessage)
        {
            if (GameMode != GameMode.InFlashcard)
                return;
            if (channelMessage.Command != ChannelCommand.NoteOn)
                return;

            var receivedNote = Note.FromMIDI(channelMessage.Data1);
            bool correct = false;
            bool flashcardFinished = false;

            if (!_currentResponse.ContainsKey(receivedNote)) // incorrect note.
            {
                correct = false;
                flashcardFinished = true;

                // play the flashcard out on the MIDI device so the user hears the correct answer.
                if (_outputDevice != null)
                    PlayFlashcard(_currentFlashcard);
            }
            else
            {
                correct = true;
                _currentResponse[receivedNote] = true; // mark the note as complete.
                flashcardFinished = _currentResponse.Values.All(r => r); // if we got them all, the flashcard is correct.
            }

            if (flashcardFinished)
            {
                _flashcardTimer.Stop();
                GameMode = GameMode.BetweenFlashcards;
                FlashcardResult result;
                int points;
                if (correct)
                {
                    result = FlashcardResult.Correct(_currentFlashcard, _currentFlashcardStartTime);
                    points = POINTS_CORRECT;
                }
                else
                {
                    result = FlashcardResult.Incorrect(_currentFlashcard, _currentFlashcardStartTime);
                    points = POINTS_INCORRECT;
                }

                Points += points;
                _flashcardResults.Add(result);

                if (FlashcardResponded != null)
                    FlashcardResponded(this, new FlashcardResultEventArgs(result));
                _nextFlashcardTimer.Start();
            }
        }
Exemplo n.º 18
0
        private void ProcessMIDI()
        {
            Midi.Sequence _MIDISequence;

            // default MIDI tempos/milliseconds per tick
            int   tempo     = 500000;
            float msPerTick = (tempo / 48) / 1000.0f;

            _MIDISequence = new Midi.Sequence();
            _MIDISequence.Load(_sequence.MusicFile);

            if (_MIDISequence.SequenceType != Sanford.Multimedia.Midi.SequenceType.Ppqn)
            {
                MessageBox.Show("Unsupported MIDI type...sorry!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            foreach (Midi.Track t in _MIDISequence)
            {
                IEnumerator <Midi.MidiEvent> en = t.Iterator().GetEnumerator();

                while (en.MoveNext())
                {
                    Midi.MidiEvent e = en.Current;
                    switch (e.MidiMessage.MessageType)
                    {
                    // starta  new channel
                    case Sanford.Multimedia.Midi.MessageType.Channel:
                        Midi.ChannelMessage channel = (Midi.ChannelMessage)e.MidiMessage;

                        // if it's a note on command and it's in our mapping list
                        if (channel.Command == Sanford.Multimedia.Midi.ChannelCommand.NoteOn &&
                            _midiMap.ContainsKey(channel.MidiChannel) &&
                            (int)((e.AbsoluteTicks * msPerTick) / 50) < _sequence.Channels[_midiMap[channel.MidiChannel]].Data.Length)
                        {
                            // this means the note is on
                            if (channel.Data2 > 0)
                            {
                                _sequence.Channels[_midiMap[channel.MidiChannel]].Data[(int)((e.AbsoluteTicks * msPerTick) / 50)] = true;
                            }
                            else
                            {
                                // the note is off
                                _sequence.Channels[_midiMap[channel.MidiChannel]].Data[(int)((e.AbsoluteTicks * msPerTick) / 50)] = false;
                                if (chkHold.Checked)
                                {
                                    // backfill the grid
                                    for (int i = (int)((e.AbsoluteTicks * msPerTick) / 50); i > 0 && !_sequence.Channels[_midiMap[channel.MidiChannel]].Data[i]; i--)
                                    {
                                        _sequence.Channels[_midiMap[channel.MidiChannel]].Data[i] = true;
                                    }
                                }
                            }
                        }
                        // true note off...don't see this used much
                        if (channel.Command == Sanford.Multimedia.Midi.ChannelCommand.NoteOff &&
                            _midiMap.ContainsKey(channel.MidiChannel))
                        {
                            _sequence.Channels[_midiMap[channel.MidiChannel]].Data[(int)((e.AbsoluteTicks * msPerTick) / 50)] = false;
                            if (chkHold.Checked)
                            {
                                for (int i = (int)((e.AbsoluteTicks * msPerTick) / 50); i > 0 && !_sequence.Channels[_midiMap[channel.MidiChannel]].Data[i]; i--)
                                {
                                    _sequence.Channels[_midiMap[channel.MidiChannel]].Data[i] = true;
                                }
                            }
                        }
                        break;

                    case Sanford.Multimedia.Midi.MessageType.Meta:
                        Midi.MetaMessage meta = (Midi.MetaMessage)e.MidiMessage;
                        switch (meta.MetaType)
                        {
                        // again, get the tempo value
                        case Sanford.Multimedia.Midi.MetaType.Tempo:
                            tempo     = meta.GetBytes()[0] << 16 | meta.GetBytes()[1] << 8 | meta.GetBytes()[2];
                            msPerTick = (tempo / _MIDISequence.Division) / 1000.0f;
                            break;
                        }
                        break;
                    }
                }
            }
        }
 /// <summary>
 /// Initializes a new instance of the ChannelMessageBuilder class with
 /// the specified ChannelMessageEventArgs.
 /// </summary>
 /// <param name="message">
 /// The ChannelMessageEventArgs to use for initializing the ChannelMessageBuilder.
 /// </param>
 /// <remarks>
 /// The ChannelMessageBuilder uses the specified ChannelMessageEventArgs to 
 /// initialize its property values.
 /// </remarks>
 public ChannelMessageBuilder(ChannelMessage message)
 {
     Initialize(message);
 }
Exemplo n.º 20
0
        /// <summary>
        /// Play the notes from a flashcard through the output device.
        /// </summary>
        /// <param name="f"></param>
        private void PlayFlashcard(Flashcard f)
        {
            ChannelMessageBuilder cbm = new ChannelMessageBuilder();
            cbm.Command = ChannelCommand.NoteOn;
            cbm.Data2 = 75;
            cbm.MidiChannel = 0;
            cbm.Build();
            cbm.Command = ChannelCommand.NoteOff;
            var onMessages = new ChannelMessage[f.StaffNotes.Length];
            var offMessages = new ChannelMessage[f.StaffNotes.Length];

            for (var i = 0; i < f.StaffNotes.Length; i++)
            {
                cbm.Data1 = f.StaffNotes[i].NoteRepresentation.Note.MIDINumber;
                cbm.Command = ChannelCommand.NoteOn;
                cbm.Build();
                onMessages[i] = cbm.Result;
                cbm.Command = ChannelCommand.NoteOff;
                cbm.Build();
                offMessages[i] = cbm.Result;
            }

            var t = new Timer(500) { AutoReset = false };
            t.Elapsed += (s, a) => Array.ForEach(offMessages, m => _outputDevice.Send(m));
            Array.ForEach(onMessages, m => _outputDevice.Send(m));
            t.Start();
        }
Exemplo n.º 21
0
        private void GetMIDIInfo(string file, bool fillTime)
        {
            Midi.Sequence MIDISequence;

            int    tempo     = 500000;
            int    maxtick   = 0;
            float  msPerTick = (tempo / 48) / 1000.0f;
            string title     = string.Empty;

            _MIDIChannels = new BindingList <MIDIChannel>();

            // load the MIDI file
            MIDISequence = new Midi.Sequence();
            MIDISequence.Load(file);

            // we don't handle non-PPQN MIDI files
            if (MIDISequence.SequenceType != Sanford.Multimedia.Midi.SequenceType.Ppqn)
            {
                MessageBox.Show("Unsupported MIDI type...sorry!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            foreach (Midi.Track t in MIDISequence)
            {
                // get the command enumerator
                IEnumerator <Midi.MidiEvent> en = t.Iterator().GetEnumerator();
                bool channelAdded = false;
                while (en.MoveNext())
                {
                    Midi.MidiEvent e = en.Current;
                    switch (e.MidiMessage.MessageType)
                    {
                    case Sanford.Multimedia.Midi.MessageType.Channel:                                   // track the # of channels
                        Midi.ChannelMessage channel = (Midi.ChannelMessage)e.MidiMessage;
                        if (!channelAdded)
                        {
                            _MIDIChannels.Add(new MIDIChannel(channel.MidiChannel, title));
                            channelAdded = true;
                        }
                        break;

                    case Sanford.Multimedia.Midi.MessageType.Meta:
                        Midi.MetaMessage meta = (Midi.MetaMessage)e.MidiMessage;
                        switch (meta.MetaType)
                        {
                        // cache away the track name for the grid
                        case Sanford.Multimedia.Midi.MetaType.TrackName:
                            title = Encoding.ASCII.GetString(meta.GetBytes());
                            break;

                        // get the tempo and convert to a time value we can use
                        case Sanford.Multimedia.Midi.MetaType.Tempo:
                            tempo     = meta.GetBytes()[0] << 16 | meta.GetBytes()[1] << 8 | meta.GetBytes()[2];
                            msPerTick = (tempo / MIDISequence.Division) / 1000.0f;
                            break;
                        }
                        break;
                    }

                    // find the highest time value
                    if (e.AbsoluteTicks > maxtick)
                    {
                        maxtick = e.AbsoluteTicks;
                    }
                }
            }
            // and use that value to fill in the minutes/seconds
            if (fillTime)
            {
                txtMinutes.Text = (((int)(msPerTick * maxtick) / 1000) / 60).ToString();
                txtSeconds.Text = (((int)(msPerTick * maxtick) / 1000) % 60 + 1).ToString();
            }
        }
Exemplo n.º 22
0
        /// <summary>
        /// Stop note
        /// </summary>
        /// <param name="note">Note number</param>
        /// <param name="v">Velocity</param>
        public void StopNote(int note, int v)
        {
            ChannelMessage mess = new ChannelMessage(ChannelCommand.NoteOff, 0, note, v);

            outDevice.Send(mess);
        }
        private void Write(ChannelMessage message)
        {
            if (runningStatus != message.Status)
            {
                trackData.Add((byte)message.Status);
                runningStatus = message.Status;
            }

            trackData.Add((byte)message.Data1);

            if (ChannelMessage.DataBytesPerType(message.Command) == 2)
            {
                trackData.Add((byte)message.Data2);
            }
        }
Exemplo n.º 24
0
        public void Send(ChannelMessage message)
        {
            if (message.Command == ChannelCommand.NoteOn &&
                message.Data1 >= LowNoteID && message.Data1 <= HighNoteID)
            {
                if (message.Data2 > 0)
                {
                    if (!dicNotesOn.ContainsKey(message.Data1))
                    {
                        var row = 0;
                        var col = 0;
                        var stringId = 0;
                        Rectangle stringRect = null;

                        //We look for the StringInfo matching the
                        //note information
                        var stringInfoQuery = from si in stringInfos
                                              where message.Data1 >= si.Min && message.Data1 <= si.Max
                                              select si;

                        if (stringInfoQuery.Any())
                        {
                            var stringInfo = stringInfoQuery.First();
                            row = stringInfo.Row;
                            col = message.Data1 - stringInfo.Min;
                            stringRect = stringInfo.Rect;
                            stringId = stringInfo.Row;
                        }

                        if (stringRect != null)
                        {
                            stringRect.Stroke =
                            stringRect.Fill = stringOnColor;
                            stringRect.Height = 1;
                        }

                        //This border shows which note
                        //is being played
                        var noteOn = new Border()
                        {
                            Width = 12,
                            Height = 12,
                            Background = innerColor,
                            BorderBrush = outerColor,
                            Tag = stringId,
                            CornerRadius = new CornerRadius(2, 2, 2, 2)
                        };

                        //This text block displays
                        //the fret number
                        var txt = new TextBlock()
                        {
                            Text = col.ToString(),
                            Foreground = fontBrush,
                            HorizontalAlignment = System.Windows.HorizontalAlignment.Center,
                            VerticalAlignment = System.Windows.VerticalAlignment.Center,
                            FontWeight = FontWeights.Bold,
                            FontSize = 10
                        };

                        noteOn.Child = txt;

                        noteOn.SetValue(Grid.RowProperty, row);
                        noteOn.SetValue(Grid.ColumnProperty, col);
                        dicNotesOn.Add(message.Data1, noteOn);
                        grdArm.Children.Add(noteOn);
                    }
                }
                else if (message.Data2 == 0)
                {
                    if (dicNotesOn.ContainsKey(message.Data1))
                    {
                        var noteOff = dicNotesOn[message.Data1];
                        dicNotesOn.Remove(message.Data1);
                        grdArm.Children.Remove(noteOff);

                        var stringId = (int)noteOff.Tag;
                        TurnOffString(stringId);
                    }
                }
            }
            else if (message.Command == ChannelCommand.NoteOff)
            {
                if (dicNotesOn.ContainsKey(message.Data1))
                {
                    var noteOff = dicNotesOn[message.Data1];
                    dicNotesOn.Remove(message.Data1);
                    grdArm.Children.Remove(noteOff);

                    var stringId = (int)noteOff.Tag;
                    TurnOffString(stringId);
                }
            }
        }
Exemplo n.º 25
0
    public static NotationTrack parseMidiTrack(Midi.Track track, int division, ref Regex fingerPattern)
    {
        int microsecondsPerBeat = Midi.PpqnClock.DefaultTempo;

        float time = 0;

        TrackStatus    trackStatus = new TrackStatus();
        FingerChordMap fingerMap   = new FingerChordMap();

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

        Regex fingerMetaPattern = new Regex("fingering-marker-pattern:(.*)");

        string name = "";

        foreach (Midi.MidiEvent e in track.Iterator())
        {
            time += e.DeltaTicks * microsecondsPerBeat / (division * 1000);

            switch (e.MidiMessage.MessageType)
            {
            case Midi.MessageType.Meta:
                Midi.MetaMessage mm = e.MidiMessage as Midi.MetaMessage;
                switch (mm.MetaType)
                {
                case Midi.MetaType.Tempo:
                    Midi.TempoChangeBuilder builder = new Midi.TempoChangeBuilder(mm);
                    microsecondsPerBeat = builder.Tempo;

                    break;

                case Midi.MetaType.Text:
                {
                    string text  = Encoding.Default.GetString(mm.GetBytes());
                    var    match = fingerMetaPattern.Match(text);
                    if (match.Success)
                    {
                        fingerPattern = new Regex(match.Groups[1].ToString());
                        Debug.LogFormat("Finger Pattern found: {0}", fingerPattern.ToString());
                    }
                }

                break;

                case Midi.MetaType.Marker:
                    if (fingerPattern != null)
                    {
                        string text  = Encoding.Default.GetString(mm.GetBytes());
                        var    match = fingerPattern.Match(text);
                        if (match.Success)
                        {
                            //Debug.LogFormat("Finger: {0}", text);
                            try
                            {
                                int    pitch  = int.Parse(match.Groups[1].ToString());
                                Finger finger = (Finger)int.Parse(match.Groups[2].ToString());

                                if (!fingerMap.ContainsKey(e.AbsoluteTicks))
                                {
                                    fingerMap[e.AbsoluteTicks] = new FingerChord();
                                }

                                fingerMap[e.AbsoluteTicks][pitch] = finger;
                            }
                            catch (System.Exception except)
                            {
                                Debug.LogWarningFormat("fingering marker parse failed: {0}, {1}", text, except.Message);
                            }
                        }
                        //else
                        //	Debug.LogWarningFormat("fail marker: {0}", text);
                    }

                    break;

                case Midi.MetaType.TrackName:
                    name = Encoding.Default.GetString(mm.GetBytes());

                    break;
                }

                break;

            case Midi.MessageType.Channel:
                Midi.ChannelMessage cm = e.MidiMessage as Midi.ChannelMessage;

                if (!trackStatus.ContainsKey(cm.MidiChannel))
                {
                    trackStatus[cm.MidiChannel] = new ChannelStatus();
                }

                var commandType = cm.Command;
                if (commandType == Midi.ChannelCommand.NoteOn && cm.Data2 == 0)
                {
                    commandType = Midi.ChannelCommand.NoteOff;
                }

                switch (commandType)
                {
                case Midi.ChannelCommand.NoteOn:
                {
                    int pitch    = cm.Data1;
                    int velocity = cm.Data2;

                    if (pitch >= Piano.PitchMin && pitch <= Piano.PitchMax)
                    {
                        trackStatus[cm.MidiChannel][pitch] = new PitchStatus {
                            tick = e.AbsoluteTicks, startTime = time, velocity = velocity
                        }
                    }
                    ;
                }

                break;

                case Midi.ChannelCommand.NoteOff:
                {
                    int pitch = cm.Data1;

                    if (!trackStatus[cm.MidiChannel].ContainsKey(pitch))
                    {
                        Debug.LogWarningFormat("Unexpected noteOff: {0}, {1}", e.AbsoluteTicks, pitch);
                    }
                    else
                    {
                        PitchStatus status = trackStatus[cm.MidiChannel][pitch];

                        Note note = new Note {
                            tick = status.tick, start = status.startTime, duration = time - status.startTime, pitch = pitch, velocity = status.velocity
                        };

                        if (fingerMap.ContainsKey(note.tick) && fingerMap[note.tick].ContainsKey(note.pitch))
                        {
                            note.finger = fingerMap[note.tick][note.pitch];
                        }

                        notes.Add(note);
                    }
                }

                break;
                }

                break;
            }
        }

        NotationTrack notation = new NotationTrack();

        notation.notes = notes.ToArray();
        notation.name  = name;

        return(notation);
    }
Exemplo n.º 26
0
 /// <summary>
 /// Initializes a new instance of the ChannelMessageBuilder class with
 /// the specified ChannelMessageEventArgs.
 /// </summary>
 /// <param name="message">
 /// The ChannelMessageEventArgs to use for initializing the ChannelMessageBuilder.
 /// </param>
 /// <remarks>
 /// The ChannelMessageBuilder uses the specified ChannelMessageEventArgs to
 /// initialize its property values.
 /// </remarks>
 public ChannelMessageBuilder(ChannelMessage message)
 {
     Initialize(message);
 }
Exemplo n.º 27
0
 public void AddToTrack(Track track, double secondToTickMultiplier)
 {
     int startAbsoluteTick = (int)((StartTime + Program.MIDIPlaybackOffset) / secondToTickMultiplier);
     int endAbsoluteTick = (int)((EndTime + Program.MIDIPlaybackOffset) / secondToTickMultiplier);
     ChannelMessage startMessage = new ChannelMessage(ChannelCommand.NoteOn, 0, NoteIndex - Program.MIDI_OFFSET, Program.MIDIPlayer.Volume);
     ChannelMessage endMessage = new ChannelMessage(ChannelCommand.NoteOff, 0, NoteIndex - Program.MIDI_OFFSET);
     try
     {
         track.Insert(startAbsoluteTick, startMessage);
         track.Insert(endAbsoluteTick, endMessage);
     }
     catch (Exception) { }
 }
Exemplo n.º 28
0
        private static void TestMerge()
        {
            Track a = new Track();
            Track b = new Track();

            a.Merge(b);

            Debug.Assert(a.Count == 1);

            ChannelMessage message = new ChannelMessage(ChannelCommand.NoteOff, 0, 60, 0);

            b.Insert(0, message);
            b.Insert(10, message);
            b.Insert(20, message);
            b.Insert(30, message);
            b.Insert(40, message);

            a.Merge(b);

            Debug.Assert(a.Count == 1 + b.Count - 1);

            a.Clear();

            Debug.Assert(a.Count == 1);

            a.Insert(0, message);
            a.Insert(10, message);
            a.Insert(20, message);
            a.Insert(30, message);
            a.Insert(40, message);

            int count = a.Count;

            a.Merge(b);

            Debug.Assert(a.Count == count + b.Count - 1);
            Debug.Assert(a.GetMidiEvent(0).DeltaTicks == 0);
            Debug.Assert(a.GetMidiEvent(1).DeltaTicks == 0);
            Debug.Assert(a.GetMidiEvent(2).DeltaTicks == 10);
            Debug.Assert(a.GetMidiEvent(3).DeltaTicks == 0);
            Debug.Assert(a.GetMidiEvent(4).DeltaTicks == 10);
            Debug.Assert(a.GetMidiEvent(5).DeltaTicks == 0);
            Debug.Assert(a.GetMidiEvent(6).DeltaTicks == 10);
            Debug.Assert(a.GetMidiEvent(7).DeltaTicks == 0);
            Debug.Assert(a.GetMidiEvent(8).DeltaTicks == 10);
            Debug.Assert(a.GetMidiEvent(9).DeltaTicks == 0);
        }
Exemplo n.º 29
0
 public ChannelMessageEventArgs(ChannelMessage message)
 {
     this.message = message;
 }
Exemplo n.º 30
0
 public static string GetID(ChannelMessage message)
 {
     if (message != null)
     {
         return GetID(message.Command, message.MidiChannel, message.Data1, message.Data2);
     }
     return null;
 }
        public virtual void Send(ChannelMessage message)
        {
            #region Require

            if (IsDisposed)
            {
                throw new ObjectDisposedException(this.GetType().Name);
            }

            #endregion

            Send(message.Message);
        }
 public ChannelMessageEventArgs(ChannelMessage message, int absoluteTicks = -1)
 {
     this.message       = message;
     this.AbsoluteTicks = absoluteTicks;
 }