Esempio n. 1
0
 void OnNoteOn(MidiMessage midi)
 {
     if(midi.data1 == 0x5E) { // FX depth knob
     //			m_sliderVal = midi.data2 - 0x40;
         var scale = midi.data2;
         transform.localScale = new Vector3(scale, scale, scale);
     }
 }
Esempio n. 2
0
 void OnNoteOn(MidiMessage midi)
 {
     if(midi.data1 == 0x5D) { // slider
     } else if(midi.data1 == 0x0C) { // x
         var data = midi.data2 - 0x40;
         rad = -data * 0.1f;
     } else if(midi.data1 == 0x0D) { // y
         var data = midi.data2 - 0x40;
         height = data;
     }
 }
Esempio n. 3
0
 void OnNoteOn(MidiMessage midi)
 {
     if(midi.data1 == 0x5D) { // slider
         renderer.material.SetColor("_Color", new Color(midi.data2 / 255f, (midi.data1 - 128f * Random.Range(0f, 2f))/255f, midi.data1 * Random.Range(0f, 1f)));
     } else if(midi.data1 == 0x0C) { // x
         var data = midi.data2 - 0x40;
         renderer.material.SetVector("_RotVector", new Vector3(data, 0f));
     //			rad = -data * 0.1f;
     } else if(midi.data1 == 0x0D) { // y
         var data = midi.data2 - 0x40;
         renderer.material.SetVector("_RotVector", new Vector3(0f, data));
     //			height = data;
     }
 }
Esempio n. 4
0
    void OnNoteOff(MidiMessage midi)
    {
        int note = midi.data1;

        NoteInfo niFound = null;
        foreach (var ni in noteInfoList) {
            if (ni.note == note) {
                niFound = ni;
                break;
            }
        }

        if (niFound != null) {
            foreach (var e in niFound.elements) {
                e.GetComponent<Element> ().StartShrink ();
            }
            noteInfoList.Remove (niFound);
        }
    }
    void Update()
    {
        while (true) {
            var data = UnityMidiReceiver.DequeueIncomingData ();
            if (data == 0) {
                break;
            }

            var message = new MidiMessage (data);
            messageQueue.Enqueue (message);
        #if UNITY_EDITOR
            messageHistory.Enqueue (message);
        #endif
        }
        #if UNITY_EDITOR
        while (messageHistory.Count > 8) {
            messageHistory.Dequeue ();
        }
        #endif
    }
Esempio n. 6
0
    void OnNoteOn(MidiMessage midi)
    {
        int note = midi.data1;
        int velocity = midi.data2;

        foreach (var ni in noteInfoList) {
            if (ni.note == note)
                return;
        }

        int numElements = Mathf.Max (8 * velocity / 128, 1);

        var noteInfo = new NoteInfo (note);
        for (var i = 0; i < numElements; i++) {
            var element = Instantiate (prefab, transform.position, Random.rotation) as GameObject;
            noteInfo.elements.Add (element);
            element.GetComponent<Element> ().ApplyMidiMessage (midi);
        }

        noteInfoList.Add (noteInfo);
    }
Esempio n. 7
0
 protected void TransmitImmediate(MidiMessage message)
 {
     transmitter.TransmitImmediate(message);
 }
Esempio n. 8
0
 public void SendChangeControl(int controller, int value, int channel)
 {
     device.Send(MidiMessage.ChangeControl(controller, value, channel).RawData);
 }
Esempio n. 9
0
        void Owner_MessageReceived(object sender, MidiMessage message, int channel, int key, int value)
        {
            if (ControlMap != null)
            {
                if (message == MidiMessage.AfterTouch || message == MidiMessage.None)
                {
                    return;
                }
                if (firstMessageReceived)
                {
                    if (ControlMap.ID != key || ControlMap.Channel != channel)
                    {
                        return;
                    }

                    if ((firstMessage == MidiMessage.NoteOn && message == MidiMessage.NoteOff) || (firstMessage == MidiMessage.NoteOff && message == MidiMessage.NoteOn))
                    {
                        ControlMap.ControlType = ControlType.KeyPress;
                    }
                    else if (firstMessage == MidiMessage.Control && firstValue == 127 && message == MidiMessage.Control && value == 0)
                    {
                        ControlMap.ControlType = ControlType.KeyPress;
                    }
                    else if ((firstMessage == MidiMessage.Control && firstValue == 127 && message == MidiMessage.Control && value == 1) ||
                             (firstMessage == MidiMessage.Control && firstValue == 1 && message == MidiMessage.Control && value == 127) ||
                             (firstMessage == MidiMessage.Control && firstValue == 1 && message == MidiMessage.Control && value == 1) ||
                             (firstMessage == MidiMessage.Control && firstValue == 127 && message == MidiMessage.Control && value == 127)
                             )
                    {
                        ControlMap.ControlType = ControlType.Jog;
                    }
                    else if (message == MidiMessage.Control && ((firstValue < 2 && value < 2) || (firstValue == 127 && value == 126) || (firstValue > 0 && firstValue < 127 && value > 1 && value < 127)))
                    {
                        ControlMap.ControlType = ControlType.Slider;
                    }
                }
                else
                {
                    firstMessageReceived = true;
                    firstMessage         = message;
                    firstValue           = value;
                    ControlMap.ID        = key;
                    ControlMap.Channel   = channel;
                    ControlMap.Name      = key.ToString();
                    return;
                }
            }

            MethodInvoker doIt = delegate
            {
                MidiMap.UnhandledMessageReceived -= new MIDI.MidiMessageReceived(Owner_MessageReceived);
                EnableControlUi();
            };

            if (this.InvokeRequired)
            {
                try
                {
                    this.Invoke(doIt);
                }
                catch
                {
                }
            }
            else
            {
                doIt();
            }
        }
Esempio n. 10
0
 private void AddEvent(int track, int tick, MidiMessage message)
 {
     _midiFile.Tracks[track].AddEvent(new MidiEvent(tick, message));
 }
Esempio n. 11
0
 /// <summary>
 /// Converts a raw MIDI message into an event ready to be
 /// sent to an implant, or returns null if the data would
 /// be useless.
 /// </summary>
 public abstract ImplantEvent Convert(MidiMessage midi);
Esempio n. 12
0
 public void ApplyMidiMessage(MidiMessage message)
 {
     targetScale = message.data2 * 1.5f / 128;
     noiseBase   = message.data1;
 }
Esempio n. 13
0
        private static void Receive()
        {
            if (!NetworkAvailable)
                return;

            SocketAsyncEventArgs eventArgs = GetEventArgs(_outEndpoint, new Byte[3]);

            eventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
            {
                if (e.SocketError == SocketError.Success && e.BytesTransferred == 3)
                {
                    Debug.WriteLine("DSMI: Midi Message Received {0} {1} {2}", e.Buffer[0], e.Buffer[1], e.Buffer[2]);

                    byte message = e.Buffer[0];
                    byte data1 = e.Buffer[1];
                    byte data2 = e.Buffer[2];
                    byte channel = (byte)(message & 0x0F);

                    MidiMessage midiMessage;

                    if ((message & MidiMessageType.MIDI_CC) == MidiMessageType.MIDI_CC)
                    {
                        midiMessage = new MidiControlChange(channel, data1, data2);

                        if (ControlChangeReceivedHandler != null)
                            ControlChangeReceivedHandler(new MidiMessageReceivedEventArgs(midiMessage));
                    }
                    else if ((message & MidiMessageType.MIDI_PC) == MidiMessageType.MIDI_PC)
                    {
                        midiMessage = new MidiProgramChange(channel, data1);

                        if (ProgramChangeReceivedHandler != null)
                            ProgramChangeReceivedHandler(new MidiMessageReceivedEventArgs(midiMessage));
                    }
                    else if ((message & MidiMessageType.NOTE_ON) == MidiMessageType.NOTE_ON)
                    {
                        midiMessage = new MidiNoteOn(channel, data1, data2);

                        if (NoteOnReceivedHandler != null)
                            NoteOnReceivedHandler(new MidiMessageReceivedEventArgs(midiMessage));
                    }
                    else if ((message & MidiMessageType.NOTE_OFF) == MidiMessageType.NOTE_OFF)
                    {
                        midiMessage = new MidiNoteOff(channel, data1, data2);

                        if (NoteOffReceivedHandler != null)
                            NoteOffReceivedHandler(new MidiMessageReceivedEventArgs(midiMessage));
                    }
                    else if ((message & MidiMessageType.MIDI_AT) == MidiMessageType.MIDI_AT)
                    {
                        midiMessage = new MidiAftertouch(channel, data1, data2);

                        if (AftertouchReceivedHandler != null)
                            AftertouchReceivedHandler(new MidiMessageReceivedEventArgs(midiMessage));
                    }
                    else
                    {
                        midiMessage = new MidiMessage(message, data1, data2);
                    }

                    if (MessageReceivedHandler != null)
                        MessageReceivedHandler(new MidiMessageReceivedEventArgs(midiMessage));
                }
                Receive();
            });
            try
            {
                _inSocket.ReceiveFromAsync(eventArgs);
            }
            catch
            {
                _inSocket.Bind(_inEndpoint);
                Receive();
            }
        }
Esempio n. 14
0
    public void onRecord(MidiMessage message)
    {
        var recordTime = Time.timeSinceLevelLoad - startTime;

        track.Record(recordTime, message.originalData);
    }
Esempio n. 15
0
			private void OnMessage(int handle, int msg, int instance, int param1, int param2)
	        {
	            if(msg == MIM_DATA || msg == MIM_ERROR || msg == MIM_LONGDATA)
	            {
	            	MidiMessage message = new MidiMessage(handle,msg,instance,param1,param2);
	            	Console.WriteLine(message.ToString());
	                OnMidiMessage(message);
	            }  
	        }
Esempio n. 16
0
        // Parse a midi message from a midi input MIM_DATA message
        public static MidiEvent ParseMimDataMessage(uint p1, uint p2)
        {
            MidiMessage message = ParseShortMessage(p1);

            return(new MidiEvent(message, p2));
        }
Esempio n. 17
0
        // Parse a midi message from a midi input MIM_DATA message
        private static MidiMessage ParseShortMessage(uint message)
        {
            MidiMessage  result     = null;
            uint         rawCommand = message & 0xff;
            uint         channel    = (rawCommand & 0x0f) + 1;
            EMidiCommand command    = (EMidiCommand)(rawCommand & 0xF0);

            if (command == EMidiCommand.SystemMessageMask)
            {
                // System message
                channel = 0;
                command = (EMidiCommand)rawCommand;

                switch (command)
                {
                case EMidiCommand.TimingClock:
                    result = new TimingClockMessage();
                    break;

                case EMidiCommand.StartSequence:
                    result = new StartSequenceMessage();
                    break;

                case EMidiCommand.ContinueSequence:
                    result = new ContinueSequenceMessage();
                    break;

                case EMidiCommand.StopSequence:
                    result = new StopSequenceMessage();
                    break;

                case EMidiCommand.ActiveSensing:
                    result = new ActiveSensingMessage();
                    break;
                }
            }
            else
            {
                uint p1 = (message >> 8) & 0xff;
                uint p2 = (message >> 16) & 0xff;

                // Common message
                switch (command)
                {
                case EMidiCommand.NoteOff:
                case EMidiCommand.NoteOn:
                case EMidiCommand.KeyAfterTouch:
                    result = new MidiNoteMessage(channel, command, p1, p2);
                    break;

                case EMidiCommand.ControlChange:
                    result = new MidiControlChangeMessage(channel, p1, p2);
                    break;

                case EMidiCommand.PatchChange:
                    result = new MidiPatchChangeMessage(channel, p1);
                    break;

                case EMidiCommand.ChannelAfterTouch:
                    result = new MidiChannelAfterTouchMessage(channel, p1);
                    break;

                case EMidiCommand.PitchWheelChange:
                    result = new MidiPitchChangeMessage(channel, p1 + (p2 << 7));
                    break;
                }
            }

            return(result);
        }
Esempio n. 18
0
        protected override void OnPaint(PaintEventArgs e)
        {
            //base.OnPaint(e);

            if (mseq == null || mseq.mdata == null)
            {
                string message = "No data - Load a midi file to view notes";
                Font   f       = new Font("Arial", 12);

                var sz = e.Graphics.MeasureString(message, f);
                e.Graphics.DrawString(message, f, Brushes.Black, new Point((int)(this.Width - sz.Width) / 2, this.Height / 2));
            }
            else
            {
                MidiMessage[] mdata    = mseq.mdata;
                double        time     = 0;
                int           maxPixel = this.Width;

                //Dictionary<int, List<Tuple<double, MidiMessage>>> last = new Dictionary<int, List<Tuple<double, MidiMessage>>>();
                Dictionary <int, List <Nullable <MidiMessage> > > last = new Dictionary <int, List <MidiMessage?> >();
                //Dictionary<int, double> currentPixel = new Dictionary<int, double>();
                //Dictionary<int, List<double>> lastTime = new Dictionary<int,List<double>>();



                RectTop    = new Dictionary <byte, int>();
                RectHeight = (this.Height - channels.Count) / (double)(channels.Count + 1);
                if (RectHeight < 15)
                {
                    RectHeight = 15;
                }


                Font fontSmall = new System.Drawing.Font("Arial", 9);
                Font fontLarge = new System.Drawing.Font("Arial", 9);
                for (int fSz = 6; fSz < 24; fSz++)
                {
                    Font  newFont = new System.Drawing.Font("Arial", fSz);
                    SizeF sz      = e.Graphics.MeasureString("MMM", newFont);
                    if (sz.Height < RectHeight / 2 && sz.Width < (LeftPriMargin) && sz.Width < (LeftMargin - LeftPriMargin))
                    {
                        fontLarge = newFont;
                    }
                }

                var lashd = e.Graphics.MeasureString("M", fontSmall);

                int i = 0;
                foreach (byte channel in channels)
                {
                    RectTop[channel] = (int)Math.Round((i + 1) * (RectHeight + 1));
                    e.Graphics.DrawString(channel.ToString(), fontLarge, mseq.IsChannelMuted(channel) ? Brushes.Red : Brushes.Green, new Point(2, RectTop[channel] + (int)((RectHeight - lashd.Height) / 2)));

                    if (ChannelPriorities.ContainsKey(channel))
                    {
                        int pri = ChannelPriorities[channel];
                        e.Graphics.DrawString(pri.ToString(), fontLarge, mseq.IsChannelMuted(channel) ? Brushes.Red : Brushes.Green, new Point(LeftPriMargin, RectTop[channel] + (int)((RectHeight - lashd.Height) / 2)));
                    }
                    i++;
                }

                e.Graphics.DrawString("Ch#", fontSmall, Brushes.Black, new Point(2, 2));
                e.Graphics.DrawString("Pri", fontSmall, Brushes.Black, new Point(LeftPriMargin, 2));


                foreach (MidiMessage mm in mdata)
                {
                    if (mm.channel == 255)
                    {
                        continue;
                    }

                    time = (double)mm.delta;

                    bool drawStart = time >= TimeOffset_samples - this.Width * SamplesPerPixel;
                    bool drawEnd   = time >= TimeOffset_samples + 2 * this.Width * SamplesPerPixel;

                    if (drawEnd)
                    {
                        break;
                    }
                    if (drawStart)
                    {
                        if (last.ContainsKey(mm.channel))
                        {
                            var thisChannel = last[mm.channel];
                            var previous    = thisChannel.FirstOrDefault(pmm => pmm.Value.data1 == mm.data1);
                            if (previous == null || previous.Value.data1 == 0)
                            {
                                previous = null;
                            }


                            if (previous != null)
                            {
                                MidiMessage prev = previous.Value;


                                float  startPixel = (float)((prev.delta - TimeOffset_samples) / SamplesPerPixel) + LeftMargin;
                                double numPixels  = (time - prev.delta) / SamplesPerPixel;

                                float height  = (float)(RectHeight / (chordCount[mm.channel]));
                                int   index   = thisChannel.Count - 1;
                                float yOffset = RectTop[mm.channel] + index * height;


                                RectangleF noteRect = new RectangleF(startPixel, yOffset, (float)numPixels, height);

                                //if (thisChannel.Count > 1)
                                //{
                                //    Trace.WriteLine(String.Format("Note {0} drawn in rectangle {1} with idx {2}.", mm, noteRect, index));
                                //}

                                if (noteRect.Right > LeftMargin)
                                {
                                    if (noteRect.Left < LeftMargin)
                                    {
                                        noteRect = new RectangleF(LeftMargin, noteRect.Top, noteRect.Right - LeftMargin, noteRect.Height);
                                    }

                                    if (numPixels >= 1)
                                    {
                                        e.Graphics.FillRectangle(GetBrush(prev, minFreq, maxFreq), noteRect);
                                    }
                                }

                                if (mm.command == (int)MidiEventTypeEnum.NoteOff)
                                {
                                    string noteText       = LaserMuzak.GetNoteStr(mm.data1);
                                    var    sz             = e.Graphics.MeasureString(noteText, fontSmall);
                                    int    noteTextOffset = 1;
                                    if (numPixels > sz.Width + 2 * noteTextOffset && height > sz.Height + 2 * noteTextOffset)
                                    {
                                        PointF loc = new PointF(startPixel + noteTextOffset, (float)yOffset + (height - sz.Height) / 2);
                                        if (loc.X >= LeftMargin)
                                        {
                                            e.Graphics.DrawString(noteText, fontSmall, Brushes.Black, loc);
                                        }
                                    }

                                    last[mm.channel].Remove(prev);
                                }
                            }
                        }

                        //while(last.Count > 1)
                        //    last[mm.channel].RemoveAt(0);

                        if (mm.command == (int)MidiEventTypeEnum.NoteOn)
                        {
                            if (last.ContainsKey(mm.channel))
                            {
                                last[mm.channel].Add(mm);
                            }
                            else
                            {
                                last.Add(mm.channel, new List <MidiMessage?>()
                                {
                                    mm
                                });
                            }
                        }

                        //currentPixel[mm.channel] += numPixels;
                        //lastTime[mm.channel] = time;
                    }
                }

                foreach (var Y in RectTop.Values)
                {
                    e.Graphics.DrawLine(Pens.Black, 0, Y, this.Width, Y);
                }

                e.Graphics.DrawLine(Pens.Black, LeftMargin, 0, LeftMargin, this.Height);
                e.Graphics.DrawLine(Pens.Black, LeftPriMargin, 0, LeftPriMargin, this.Height);

                MidiMessage endMM    = mdata[mdata.Length - 1];
                double      lastTime = (double)endMM.delta;
                foreach (var ch in last.Keys)
                {
                    var thisChannel = last[ch];
                    foreach (var previous in thisChannel)
                    {
                        var prev = previous.Value;

                        float  startPixel = (float)((prev.delta - TimeOffset_samples) / SamplesPerPixel) + LeftMargin;
                        double numPixels  = (time - prev.delta) / SamplesPerPixel;

                        float height  = (float)(RectHeight / (thisChannel.Count));
                        int   index   = thisChannel.IndexOf(previous);
                        float yOffset = RectTop[(byte)ch] + index * height;

                        if (numPixels >= 1)
                        {
                            e.Graphics.FillRectangle(GetBrush(prev, minFreq, maxFreq), new RectangleF(startPixel, yOffset, (float)numPixels, height));
                        }
                    }
                }



                if (SamplesPerPixel > 0)
                {
                    float timeX = (float)(LeftMargin + ((currTime) - TimeOffset_samples) / SamplesPerPixel);
                    e.Graphics.DrawLine(Pens.Green, timeX, 0, timeX, this.Height);

                    if (startTime >= 0)
                    {
                        timeX = (float)(LeftMargin + ((startTime) - TimeOffset_samples) / SamplesPerPixel);
                        e.Graphics.DrawLine(Pens.White, timeX, 0, timeX, this.Height);
                    }

                    if (endTime >= 0)
                    {
                        timeX = (float)(LeftMargin + ((endTime) - TimeOffset_samples) / SamplesPerPixel);
                        e.Graphics.DrawLine(Pens.White, timeX, 0, timeX, this.Height);
                    }
                }

                //e.Graphics.DrawString((currTime * 20).ToString(), new Font("Arial", LeftMargin), Brushes.White, new Point(10, 2 * this.Height / 4));
                //e.Graphics.DrawString(mouse_us.ToString(), new Font("Arial", LeftMargin), Brushes.White, new Point(10, 3 * this.Height / 4));
            }
        }
Esempio n. 19
0
        // Parse a midi message from a midi file
        private static MidiMessage ParseMidiMessage(MidiFileFormatReader mffr, uint runningStatus)
        {
            MidiMessage result = null;
            uint        rawCommand;
            uint        p1            = 0;
            bool        alreadyReadP1 = false;

            // Read the command
            rawCommand = mffr.ReadUInt8();

            if ((rawCommand & 0x80) == 0x80)
            {
                // New running status
                runningStatus = rawCommand;
            }
            else
            {
                // What we just read is actually p1 of a common message
                alreadyReadP1 = true;
                p1            = rawCommand;
                rawCommand    = runningStatus;
            }

            // Get channel
            uint         channel = (rawCommand & 0x0f) + 1;
            EMidiCommand command = (EMidiCommand)(rawCommand & 0xF0);

            if (command == EMidiCommand.SystemMessageMask)
            {
                // System message
                channel = 0;
                command = (EMidiCommand)rawCommand;

                switch (command)
                {
                // System messages - Exclusive
                case EMidiCommand.SystemExclusive:
                {
                    // Determine length of body + end-of-exclusive
                    uint   length    = mffr.ReadVarLengthQuantity();
                    byte[] sysexBody = new byte[length + 1];

                    // Read body
                    sysexBody[0] = (byte)EMidiCommand.SystemExclusive;
                    for (uint b = 0; b < length; b++)
                    {
                        sysexBody[b + 1] = mffr.ReadUInt8();
                    }

                    // Verify end-of-exclusive
                    if (sysexBody[length] != (byte)EMidiCommand.EndOfSystemExclusive)
                    {
                        throw new FormatException("Sysex of length " + length + " ending with " + sysexBody[length] + " instead of F7");
                    }

                    result = new MidiSysexMessage(sysexBody);
                    break;
                }

                // System messages - Common
                case EMidiCommand.SongPosition:
                case EMidiCommand.SongSelect:
                case EMidiCommand.TuneRequest:

                // System messages - Real time
                case EMidiCommand.TimingClock:
                case EMidiCommand.StartSequence:
                case EMidiCommand.ContinueSequence:
                case EMidiCommand.StopSequence:
                case EMidiCommand.ActiveSensing:
                    throw new FormatException(string.Format("Found event type {0} - not supported!", command));

                // Meta event
                case EMidiCommand.MetaEvent:
                    result = ParseMidiMetaMessage(mffr);
                    break;
                }
            }
            else
            {
                if (!alreadyReadP1)
                {
                    p1 = mffr.ReadUInt8();
                }

                // Channel message
                switch (command)
                {
                case EMidiCommand.NoteOff:
                case EMidiCommand.NoteOn:
                case EMidiCommand.KeyAfterTouch:
                    result = new MidiNoteMessage(channel, command, p1, mffr.ReadUInt8());
                    break;

                case EMidiCommand.ControlChange:
                    result = new MidiControlChangeMessage(channel, p1, mffr.ReadUInt8());
                    break;

                case EMidiCommand.PatchChange:
                    result = new MidiPatchChangeMessage(channel, p1);
                    break;

                case EMidiCommand.ChannelAfterTouch:
                    result = new MidiChannelAfterTouchMessage(channel, p1);
                    break;

                case EMidiCommand.PitchWheelChange:
                    result = new MidiPitchChangeMessage(channel, p1 + ((uint)mffr.ReadUInt8() << 7));
                    break;
                }
            }

            result.RunningStatus = runningStatus;
            return(result);
        }
        /// <summary>
        /// Create a new MIDI message based on the message type and Parameter(s) values,
        /// and send it to the chosen output device
        /// </summary>
        /// <param name="sender">Element that fired the event</param>
        /// <param name="e">Event arguments</param>
        private void SendButton_Clicked(object sender, EventArgs e)
        {
            MidiMessage midiMessageToSend = null;

            switch (this.currentMessageType)
            {
            case MidiEvent.NoteOff:
                midiMessageToSend = new MidiNoteOffMessage(Convert.ToByte(this.Parameter1.SelectedItem), Convert.ToByte(this.Parameter2.SelectedItem), Convert.ToByte(this.Parameter3.SelectedItem));
                break;

            case MidiEvent.NoteOn:
                midiMessageToSend = new MidiNoteOnMessage(Convert.ToByte(this.Parameter1.SelectedItem), Convert.ToByte(this.Parameter2.SelectedItem), Convert.ToByte(this.Parameter3.SelectedItem));
                break;

            case MidiEvent.PAf:
                midiMessageToSend = new MidiPolyphonicKeyPressureMessage(Convert.ToByte(this.Parameter1.SelectedItem), Convert.ToByte(this.Parameter2.SelectedItem), Convert.ToByte(this.Parameter3.SelectedItem));
                break;

            case MidiEvent.CC:
                midiMessageToSend = new MidiControlChangeMessage(Convert.ToByte(this.Parameter1.SelectedItem), Convert.ToByte(this.Parameter2.SelectedItem), Convert.ToByte(this.Parameter3.SelectedItem));
                break;

            case MidiEvent.Program:
                midiMessageToSend = new MidiProgramChangeMessage(Convert.ToByte(this.Parameter1.SelectedItem), Convert.ToByte(this.Parameter2.SelectedItem));
                break;

            case MidiEvent.CAf:
                midiMessageToSend = new MidiChannelPressureMessage(Convert.ToByte(this.Parameter1.SelectedItem), Convert.ToByte(this.Parameter2.SelectedItem));
                break;

            case MidiEvent.Pitch:
                midiMessageToSend = new MidiPitchBendChangeMessage(Convert.ToByte(this.Parameter1.SelectedItem), Convert.ToUInt16(this.Parameter2.SelectedItem));
                break;

            case MidiEvent.SysEx1:
                var dataWriter         = new List <byte>();
                var sysExMessage       = this.SysExMessageContent.Text;
                var sysExMessageLength = sysExMessage.Length;

                // Do not send a blank SysEx message
                if (sysExMessageLength == 0)
                {
                    return;
                }

                // SysEx messages are two characters long with 1-character space in between them
                // So we add 1 to the message length, so that it is perfectly divisible by 3
                // The loop count tracks the number of individual message pieces
                int loopCount = (sysExMessageLength + 1) / 3;

                // Expecting a string of format "F0 NN NN NN NN.... F7", where NN is a byte in hex
                for (int i = 0; i < loopCount; i++)
                {
                    var messageString = sysExMessage.Substring(3 * i, 2);
                    var messageByte   = Convert.ToByte(messageString, 16);
                    dataWriter.Add(messageByte);
                }
                midiMessageToSend = new MidiSystemExclusiveMessage(dataWriter.ToArray());
                break;

            case MidiEvent.MtcQuarterFrame:
                midiMessageToSend = new MidiTimeCodeMessage(Convert.ToByte(this.Parameter1.SelectedItem), Convert.ToByte(this.Parameter2.SelectedItem));
                break;

            case MidiEvent.SongPositionPointer:
                midiMessageToSend = new MidiSongPositionPointerMessage(Convert.ToUInt16(this.Parameter1.SelectedItem));
                break;

            case MidiEvent.SongSelect:
                midiMessageToSend = new MidiSongSelectMessage(Convert.ToByte(this.Parameter1.SelectedItem));
                break;

            case MidiEvent.TuneRequest:
                midiMessageToSend = new MidiTuneRequestMessage();
                break;

            case MidiEvent.MidiClock:
                midiMessageToSend = new MidiTimingClockMessage();
                break;

            case MidiEvent.MidiStart:
                midiMessageToSend = new MidiStartMessage();
                break;

            case MidiEvent.MidiContinue:
                midiMessageToSend = new MidiContinueMessage();
                break;

            case MidiEvent.MidiStop:
                midiMessageToSend = new MidiStopMessage();
                break;

            case MidiEvent.ActiveSense:
                midiMessageToSend = new MidiActiveSensingMessage();
                break;

            case MidiEvent.Reset:
                midiMessageToSend = new MidiSystemResetMessage();
                break;

            default:
                return;
            }

            // Send the message
            _synthesizer.SendMessage(midiMessageToSend);
            //this.rootPage.NotifyUser("Message sent successfully", NotifyType.StatusMessage);
        }
Esempio n. 21
0
        void monitoringMap_MessageReceived(object sender, MidiMessage message, int channel, int key, int value)
        {
            if (monitoringMap != null)
            {
                var map = monitoringMap.FindMap(channel, key);

                if (map != null)
                {
                    MethodInvoker doIt = delegate
                    {
                        foreach (ListViewItem item in MapsView.Items)
                        {
                            var cb = item.Tag as ControlBinding;
                            if (cb != null)
                            {
                                if (cb.Parent == map)
                                {
                                    item.Selected = true;
                                    MapsView.EnsureVisible(item.Index);
                                    break;
                                }
                            }
                        }
                    };

                    if (InvokeRequired)
                    {
                        try
                        {
                            Invoke(doIt);
                        }
                        catch
                        {
                        }
                    }
                    else
                    {
                        doIt();
                    }
                }
            }
        }
Esempio n. 22
0
		private void OnMidiMessageHandler(MidiMessage msg) 
		{
			OnMidiMessage(msg);
		}
    void Update ()
    {
        // Update the note state array.
        foreach (var cs in channelArray)
        {
            for (var i = 0; i < 128; i++)
            {
                var x = cs.noteArray [i];
                if (x > 1.0f)
                {
                    // Key down -> Hold.
                    cs.noteArray [i] = x - 1.0f;
                }
                else if (x < 0)
                {
                    // Key up -> Off.
                    cs.noteArray [i] = 0.0f;
                }
            }
        }

        // Process the message queue.
        while (true)
        {
            // Pop from the queue.
            var data = DequeueIncomingData ();
            if (data == 0)
            {
                break;
            }

            // Parse the message.
            var message = new MidiMessage (data);

            // Split the first byte.
            var statusCode = message.status >> 4;
            var channelNumber = message.status & 0xf;
            
            // Note on message?
            if (statusCode == 9)
            {
                var velocity = 1.0f / 127 * message.data2 + 1.0f;
                channelArray [channelNumber].noteArray [message.data1] = velocity;
                channelArray [(int)MidiChannel.All].noteArray [message.data1] = velocity;
            }
            
            // Note off message?
            if (statusCode == 8 || (statusCode == 9 && message.data2 == 0))
            {
                channelArray [channelNumber].noteArray [message.data1] = -1.0f;
                channelArray [(int)MidiChannel.All].noteArray [message.data1] = -1.0f;
            }
            
            // CC message?
            if (statusCode == 0xb)
            {
                // Normalize the value.
                var value = 1.0f / 127 * message.data2;
                // Update the channel if it already exists, or add a new channel.
                channelArray [channelNumber].knobMap [message.data1] = value;
                // Do again for All-ch.
                channelArray [(int)MidiChannel.All].knobMap [message.data1] = value;
            }

            #if UNITY_EDITOR
            // Record the message history.
            messageHistory.Enqueue (message);
            #endif
        }

        #if UNITY_EDITOR
        // Truncate the history.
        while (messageHistory.Count > 8) {
            messageHistory.Dequeue ();
        }
        #endif
    }
Esempio n. 24
0
 public int PopMessage(out MidiMessage midiMessage, bool editor = false)
 {
     return(MidiPlugin.MIDIIN_PopMessage(out midiMessage));
 }
Esempio n. 25
0
		private void NullMidiMessageHandler(MidiMessage msg) 
		{ }
Esempio n. 26
0
    void Update()
    {
        // Update the note state array.
        foreach (var cs in _channelArray)
        {
            for (var i = 0; i < 128; i++)
            {
                var x = cs._noteArray[i];
                if (x > 1)
                {
                    cs._noteArray[i] = x - 1;     // Key down -> Hold.
                }
                else if (x < 0)
                {
                    cs._noteArray[i] = 0;     // Key up -> Off.
                }
            }
        }

        // Process the message queue.
        while (true)
        {
            // Pop from the queue.
            var data = DequeueIncomingData();
            if (data == 0)
            {
                break;
            }

            // Parse the message.
            var message = new MidiMessage(data);

            // Split the first byte.
            var statusCode    = message.status >> 4;
            var channelNumber = message.status & 0xf;

            // Note on message?
            if (statusCode == 9)
            {
                var velocity = 1.0f / 127 * message.data2 + 1;
                _channelArray[channelNumber]._noteArray[message.data1]        = velocity;
                _channelArray[(int)MidiChannel.All]._noteArray[message.data1] = velocity;
                if (noteOnDelegate != null)
                {
                    noteOnDelegate((MidiChannel)channelNumber, message.data1, velocity - 1);
                }
            }

            // Note off message?
            if (statusCode == 8 || (statusCode == 9 && message.data2 == 0))
            {
                _channelArray[channelNumber]._noteArray[message.data1]        = -1;
                _channelArray[(int)MidiChannel.All]._noteArray[message.data1] = -1;
                if (noteOffDelegate != null)
                {
                    noteOffDelegate((MidiChannel)channelNumber, message.data1);
                }
            }

            // CC message?
            if (statusCode == 0xb)
            {
                // Normalize the value.
                var level = 1.0f / 127 * message.data2;
                // Update the channel if it already exists, or add a new channel.
                _channelArray[channelNumber]._knobMap[message.data1] = level;
                // Do again for All-ch.
                _channelArray[(int)MidiChannel.All]._knobMap[message.data1] = level;
                if (knobDelegate != null)
                {
                    knobDelegate((MidiChannel)channelNumber, message.data1, level);
                }
            }
        }
    }
 void OnNoteOn(MidiMessage midi)
 {
     particleSystem.startSize = midi.data2 / 64.0f;
     particleSystem.Emit (Mathf.Max(midi.data2 / 8, 3));
 }
Esempio n. 28
0
 public abstract void SendMessage(MidiMessage message);
Esempio n. 29
0
		private void PlayMidiThread()
        {
			System.Threading.Thread.Sleep(4000);
			MidiFileChunkMTrk mtrk = (MidiFileChunkMTrk) midiFile.ChunkMTrk[1];
			int i = 0;
        	while (!stop) {
				MidiEvent evt = (MidiEvent) mtrk.MidiEvents[i];
				//Logger.Instance.Log("DeltaTime: "+evt.DeltaTime);
        		System.Threading.Thread.Sleep(evt.DeltaTime / 50);
        		if ((evt.Status & 0xF0) == 0x90) {
	        		MidiMessage message = new MidiMessage();
					message.Status = 0x90;
					message.Note = evt.Data[0];
					message.Velocity = evt.Data[1];
					//Logger.Instance.Log(message.ToString());
		        	OnMidiMessage(message);
        		}
        		if ((evt.Status & 0xF0) == 0x80) {
	        		MidiMessage message = new MidiMessage();
					message.Status = 0x90;
					message.Note = evt.Data[0];
					message.Velocity = 0;
					//Logger.Instance.Log(message.ToString());
		        	OnMidiMessage(message);
        		}
	        	i++;
	        	if (i >= mtrk.MidiEvents.Count) i = 0;
        	}
        }		
 private static void NoteOn(int num)
 {
     midiOut.Send(MidiMessage.StartNote(num, 127, 1).RawData);
 }
Esempio n. 31
0
 private void HandleMessageReceived(object sender, MidiMessage message) =>
 MessageReceived?.Invoke(this, message);
 private static void NoteOff(int num)
 {
     midiOut.Send(MidiMessage.StopNote(num, 0, 1).RawData);
 }
    void OnGUI()
    {
        SerializedObject   so = new SerializedObject(this);
        SerializedProperty stringsProperty = so.FindProperty("knobSettingList");

        EditorGUILayout.PropertyField(stringsProperty, true); // True means show children
        so.ApplyModifiedProperties();                         // Remember to apply modified properties


        foreach (KnobSettingsContainer con in knobSettingList)
        {
            con.set();
        }


        transform = EditorGUILayout.ObjectField("root", transform, typeof(Transform), true) as Transform;
        animator  = EditorGUILayout.ObjectField("root", animator, typeof(Animator), true) as Animator;

        GUILayout.Label("MVMidiController", EditorStyles.boldLabel);



        if (GUILayout.Button("Set Orig"))
        {
            focusOnAnimation();
        }

        try {
            MidiMessage mmm = MidiDriver.Instance.History.ToArray()[MidiDriver.Instance.History.ToArray().Length - 1];
            if (mmm.data1 == 15 && mmm.data2 == 127)
            {
                focusOnAnimation();
            }
        } catch (IndexOutOfRangeException e) {
        }


        if (UnityEditor.EditorWindow.focusedWindow != null)
        {
            EditorWindow window = UnityEditor.EditorWindow.focusedWindow;

            if (window.GetType().Name == "AnimationWindow")
            {
                object obj = window.GetType().GetField("m_AnimEditor", flags).GetValue(window);

                Debug.Log("focudsed");

                if (MidiMaster.GetKey(0) != 0)
                {
                    invoke(obj, "MoveToPreviousKeyframe");
                    invoke(obj, "Repaint");
                }

                if (MidiMaster.GetKey(1) != 0)
                {
                    invoke(obj, "MoveToNextKeyframe");
                    invoke(obj, "Repaint");
                }

                if (MidiMaster.GetKey(36) != 0)
                {
                    invoke(obj, "MoveToPreviousKeyframe");
                    invoke(obj, "Repaint");
                }

                if (MidiMaster.GetKey(37) != 0)
                {
                    invoke(obj, "MoveToNextKeyframe");
                    invoke(obj, "Repaint");
                }

                Debug.Log((MidiMaster.GetKnob(0, 0f) - 0.5f) * 40 * 2f);

                try {
                    MidiMessage mm = MidiDriver.Instance.History.ToArray()[MidiDriver.Instance.History.ToArray().Length - 1];

                    if (mm.data1 == 14 && mm.data2 == 127)
                    {                       //Fastforward
                        //invoke (obj, "MoveToNextKeyframe");
                        //invoke (obj, "Repaint");

                        object obj2        = obj.GetType().GetField("m_State", flags).GetValue(obj);
                        float  currentTime = (float)obj2.GetType().GetProperty("currentTime", flags).GetValue(obj2, null);
                        float  maxTime     = (float)obj2.GetType().GetProperty("maxTime", flags).GetValue(obj2, null);
                        obj2.GetType().GetProperty("currentTime", flags).SetValue(obj2, (currentTime + 0.05f < maxTime) ? currentTime + 0.05f : maxTime, null);
                        invoke(obj, "PlaybackUpdate");
                        invoke(obj, "Repaint");
                    }
                    else if (mm.data1 == 13 && mm.data2 == 127)
                    {                       //Rewind
                        object obj2        = obj.GetType().GetField("m_State", flags).GetValue(obj);
                        float  currentTime = (float)obj2.GetType().GetProperty("currentTime", flags).GetValue(obj2, null);
                        float  maxTime     = (float)obj2.GetType().GetProperty("maxTime", flags).GetValue(obj2, null);
                        obj2.GetType().GetProperty("currentTime", flags).SetValue(obj2, (currentTime - 0.05f > 0) ? currentTime - 0.05f : 0, null);
                        invoke(obj, "PlaybackUpdate");
                        invoke(obj, "Repaint");
                    }
                    else if (mm.data1 == 10 && mm.data2 == 127)
                    {
                        //Play
                        object obj1 = obj.GetType().GetField("m_State", flags).GetValue(obj);
                        obj1.GetType().GetProperty("playing", flags).SetValue(obj1, true, null);
                        invoke(obj, "PlaybackUpdate");
                        invoke(obj, "Repaint");
                    }
                    else if (mm.data1 == 11 && mm.data2 == 127)
                    {
                        //Stop

                        // PlaybackUpdate set time to max time and call playback update
                        object obj1 = obj.GetType().GetField("m_State", flags).GetValue(obj);
                        obj1.GetType().GetProperty("playing", flags).SetValue(obj1, false, null);
                        invoke(obj, "MoveToFirstKeyframe");
                        invoke(obj, "Repaint");
                    }
                    else if (mm.data1 == 12 && mm.data2 == 127)
                    {
                        object obj1 = obj.GetType().GetField("m_State", flags).GetValue(obj);
                        obj1.GetType().GetProperty("recording", flags).SetValue(obj1, true, null);
                        invoke(obj, "Repaint");
                    }
                    else if (mm.data1 == 12 && mm.data2 == 0)
                    {
                        object obj1 = obj.GetType().GetField("m_State", flags).GetValue(obj);
                        obj1.GetType().GetProperty("recording", flags).SetValue(obj1, false, null);
                        invoke(obj, "Repaint");
                        //obj.GetType().GetField("m_PreviousUpdateTime").SetValue(obj, Time.
                    }

                    object obj22        = obj.GetType().GetField("m_State", flags).GetValue(obj);
                    float  currentTime2 = (float)obj22.GetType().GetProperty("currentTime", flags).GetValue(obj22, null);


                    Debug.Log(" data1 " + mm.data1 + " data2 " + mm.data2 + " status " + mm.status + "  " + mm.ToString());
                } catch (IndexOutOfRangeException e) {
                }
            }
        }


        ////
        ////
        ////if (transform != null) {
        ////	origEulerAngles = new Vector3 (((MidiMaster.GetKnob (0, 0f) - 0.5f) * 90),  ((MidiMaster.GetKnob (1, 0f) - 0.5f) * 90), ((MidiMaster.GetKnob (2, 0f) - 0.5f) * 90));
        ////	Vector3 newEulerAngles = origEulerAngles;
        ////	transform.localEulerAngles = newEulerAngles;
        ////}
        //Debug.Log ((MidiMaster.GetKnob (0, 0f) - 0.5f) * 180f);
    }
Esempio n. 34
0
        internal bool DispatchMessage(MidiMessage message, int channel, int key, double value)
        {
            bool currentVal = false;

            double normalizedValue = (double)value / 127.0;
            double scaledValue = Min + (Max - Min) * normalizedValue;
            int scaledValueInt = (int)scaledValue;

            IScriptable scriptInterface = null;
            switch (TargetType)
            {
                case BindingTargetType.Setting:
                    scriptInterface = Settings.Active as IScriptable;
                    break;
                case BindingTargetType.SpaceTimeController:
                    scriptInterface = SpaceTimeController.ScriptInterface;
                    break;
                case BindingTargetType.Goto:
                    Earth3d.MainWindow.GotoCatalogObject(PropertyName);
                    break;
                case BindingTargetType.Layer:
                    scriptInterface = LayerManager.ScriptInterface;
                    break;
                case BindingTargetType.Navigation:
                    scriptInterface = Earth3d.MainWindow as IScriptable;
                    break;
               //  case BindingTargetType.Actions:
               //     break;
               //case BindingTargetType.Key:
               //     break;
               // case BindingTargetType.Mouse:
               //     break;
                default:
                    break;
            }

            if (scriptInterface != null && !string.IsNullOrEmpty(PropertyName))
            {
                switch (BindingType)
                {
                    case BindingType.Action:
                        scriptInterface.InvokeAction(PropertyName, normalizedValue.ToString());
                        break;
                    case BindingType.Toggle:
                        currentVal = scriptInterface.ToggleProperty(PropertyName);
                        if (channel > -1)
                        {
                            ((MidiMap)Parent.Owner).OutputDevice.SendMessageShort((byte)(144 + channel), (byte)key, (byte)(currentVal ? 3 : 0));
                        }
                        break;
                    case BindingType.SyncValue:
                        scriptInterface.SetProperty(PropertyName, Integer ? scaledValueInt.ToString() : scaledValue.ToString());
                        break;
                    case BindingType.SetValue:
                        scriptInterface.SetProperty(PropertyName, Value.ToString());
                        break;
                    default:
                        break;
                }
            }
            return currentVal;
        }
 public void TransmitImmediate(MidiMessage message)
 {
     output.SendMessage(message);
 }
Esempio n. 36
0
 public void TransmitImmediate(MidiMessage message)
 {
     // TODO: Might want direct calls to midiOut instead
     stream.Write(new MidiEvent(-1, message));
 }
Esempio n. 37
0
        protected void TransmitEvent(MidiMessage message)
        {
            var evt = new MidiEvent(CurrentTick, message);

            transmitter.Transmit(evt);
        }
Esempio n. 38
0
 private static extern int MidiIn_PopMessage(out MidiMessage midiMessage, bool editor);
Esempio n. 39
0
        internal double GetValue(MidiMessage message, int channel, int key)
        {
            IScriptable scriptInterface = null;
            switch (TargetType)
            {
                case BindingTargetType.Setting:
                    scriptInterface = Settings.Active as IScriptable;
                    break;
                case BindingTargetType.SpaceTimeController:
                    scriptInterface = SpaceTimeController.ScriptInterface;
                    break;
                case BindingTargetType.Goto:
                    Earth3d.MainWindow.GotoCatalogObject(PropertyName);
                    break;
                case BindingTargetType.Layer:
                    scriptInterface = LayerManager.ScriptInterface;
                    break;
                case BindingTargetType.Navigation:
                    scriptInterface = Earth3d.MainWindow as IScriptable;
                    break;
                //  case BindingTargetType.Actions:
                //     break;
                //case BindingTargetType.Key:
                //     break;
                // case BindingTargetType.Mouse:
                //     break;
                default:
                    break;
            }

            double value = 0;

            if (scriptInterface != null && !string.IsNullOrEmpty(PropertyName))
            {
                try
                {
                    switch (BindingType)
                    {
                        case BindingType.Action:
                            // no values in actions
                            break;
                        case BindingType.Toggle:
                        case BindingType.SyncValue:
                            string val = scriptInterface.GetProperty(PropertyName);
                            if (!string.IsNullOrEmpty(val))
                            {
                                value = double.Parse(val);
                                value = (value - Min) / (Max - Min);
                                value = (double)value * 127.0;
                                return value;
                            }
                            return 0;
                        case BindingType.SetValue:
                            // don't scale this
                            value = double.Parse(scriptInterface.GetProperty(PropertyName));
                            return value;
                        default:
                            break;
                    }
                }
                catch
                {
                }
            }

            return 0;
        }
Esempio n. 40
0
		public void OnMidiMessageReceived(MidiMessage msg) {
			if (msg.Velocity == 0) this.OnMidiMessage(msg);
			else if ((msg.Note>=this.noteMin) && (msg.Note<=this.noteMax)) {
				MidiMessage msgCopy = new MidiMessage(msg);
				if (msgCopy.Velocity<this.velocityMin)
					msgCopy.Velocity = (int) (this.velocityMin * 127.0f);
				if (msgCopy.Velocity>this.velocityMax) 
					msgCopy.Velocity = (int) (this.velocityMax * 127.0f);
				this.OnMidiMessage(msgCopy);
			}
		}
Esempio n. 41
0
 public void TransmitImmediate(MidiMessage message)
 {
 }
Esempio n. 42
0
        internal bool DispatchMessage(MidiMessage message, int channel, int key, int value)
        {
            bool currentVal = false;

            if (ControlType == ControlType.KeyPress && (message == MidiMessage.NoteOff || value == 0))
            {
                // On note off we just turn off the mapping
                KeyDown = false;
                return currentVal;
            }

            if (ControlType == TerraViewer.ControlType.KeyUpDown && (message == MidiMessage.NoteOff || value == 0))
            {
                currentVal = BindingB.DispatchMessage(message, channel, key, value);
                KeyDown = false;
                return currentVal;
            }

            if (ControlType == TerraViewer.ControlType.Jog && (message == MidiMessage.Control && value < 64))
            {
                currentVal = BindingA.DispatchMessage(message, channel, key, value);
                return currentVal;
            }

            if (ControlType == TerraViewer.ControlType.Jog && (message == MidiMessage.Control && value > 63))
            {
                currentVal = BindingB.DispatchMessage(message, channel, key, value);
                return currentVal;
            }

            currentVal = BindingA.DispatchMessage(message, channel, key, value);
            KeyDown = true;
            return currentVal;
        }
Esempio n. 43
0
 public void Send(MidiMessage message)
 {
     // Note that we're not waiting for this to complete. That's okay, as it's
     // expected to be "fire and forget" anyway.
     runtime.InvokeVoidAsync("midi.sendMessage", port, message.Data);
 }
Esempio n. 44
0
 internal double GetValue(MidiMessage message, int channel, int key)
 {
     return BindingA.GetValue(message, channel, key);
 }
Esempio n. 45
0
 public void ApplyMidiMessage(MidiMessage message)
 {
     targetScale = message.data2 * 1.5f / 128;
     noiseBase = message.data1;
 }
Esempio n. 46
0
        void InputDevice_MessageReceived(object sender, MidiMessage message, int channel, int key, int value)
        {
            ControlMap map = null;

            map = FindMap(channel, key);

            if (MessageReceived != null)
            {
                MessageReceived.Invoke(this, message, channel, key, value);
            }

            if (map == null)
            {
                if (UnhandledMessageReceived != null)
                {
                    UnhandledMessageReceived.Invoke(this, message, channel, key, value);
                }
            }
            else
            {
                map.DispatchMessage(message, channel, key, value);
                if (map.AutoRepeat && map.KeyDown && !AutoRepeatList.Contains(map))
                {
                    AutoRepeatList.Add(map);
                }
                else if (map.AutoRepeat && !map.KeyDown && AutoRepeatList.Contains(map))
                {
                    AutoRepeatList.Remove(map);
                }

            }
        }
 public MidiMessageReceivedEventArgs(MidiMessage message)
 {
     MidiMessage = message;
 }
Esempio n. 48
0
 void AddMessage(int position, MidiMessage message)
 {
     this.message[position, msgCount[position]++] = message;
 }
Esempio n. 49
0
 public MidiInputEventArgs(MidiMessage message)
 {
     Message = message;
 }
Esempio n. 50
0
 public int PopMessage(out MidiMessage midiMessage, bool editor = false)
 {
     midiMessage = new MidiMessage();
     return(0);
 }
Esempio n. 51
0
		private void NoteOn()
		{
			MidiMessage message = new MidiMessage();
			message.Status = 0x90;
        	message.Note = rand.Next(noteMin,noteMax);
			message.Velocity = rand.Next((int)Math.Round(velocityMin*128.0),(int)Math.Round(velocityMax*128.0));
			//Logger.Instance.Log(message.ToString());
        	OnMidiMessage(message);
        	notesList.Add(message);
		}
Esempio n. 52
0
 private void OnMessage(IntPtr hMidi, MidiMessage wMsg, IntPtr dwInstance, IntPtr dwParam1, IntPtr dwParam2)
 {
     // TODO: process MOM_DONE
 }
Esempio n. 53
0
    void Update()
    {
        // Update the note state array.
        for (var i = 0; i < 128; i++) {
            var x = notes [i];
            if (x > 1.0f) {
                // Key down -> Hold.
                notes [i] = x - 1.0f;
            } else if (x < 0) {
                // Key up -> Off.
                notes [i] = 0.0f;
            }
        }

        // Calculate the filter coefficients.
        var fastFilterCoeff = Mathf.Exp (-sensibilityFast * Time.deltaTime);
        var slowFilterCoeff = Mathf.Exp (-sensibilitySlow * Time.deltaTime);

        // Update the filtered value.
        foreach (var k in knobs.Values) {
            k.UpdateFilter (fastFilterCoeff, slowFilterCoeff);
        }

        // Process the message queue.
        while (true) {
            // Pop from the queue.
            var data = DequeueIncomingData ();
            if (data == 0) {
                break;
            }

            // Parse the message.
            var message = new MidiMessage (data);

            // Note on message?
            if (message.status == 0x90) {
                notes [message.data1] = 1.0f / 127 * message.data2 + 1.0f;
            }

            // Note off message?
            if (message.status == 0x80 || (message.status == 0x90 && message.data2 == 0)) {
                notes [message.data1] = -1.0f;
            }

            // CC message?
            if (message.status == 0xb0) {
                // Normalize the value.
                var value = 1.0f / 127 * message.data2;

                // Update the channel if it already exists, or add a new channel.
                if (knobs.ContainsKey (message.data1)) {
                    knobs [message.data1].Update (value);
                } else {
                    knobs [message.data1] = new Knob (value);
                }
            }

            #if UNITY_EDITOR
            // Record the message history.
            messageHistory.Enqueue (message);
            #endif
        }

        #if UNITY_EDITOR
        // Truncate the history.
        while (messageHistory.Count > 8) {
            messageHistory.Dequeue ();
        }
        #endif
    }
        void PlayMidi(string MidFile, string Track)
        {
            List <PianoNote> NoteListEX = new List <PianoNote>();
            TempoWorker      tempo      = new TempoWorker(120, TempoWorker.NoteType.Crotchet);
            MidiRResult      MidiRecv   = MidiWorker.ReadMidi(MidFile, Track);
            NoteOnEvent      FN         = MidiRecv.Notes[0];
            long             off        = FN.AbsoluteTime;
            long             lastEnd    = 0;

            for (int i = 0; i < MidiRecv.Notes.Count; i++)
            {
                NoteOnEvent NoteEvent = MidiRecv.Notes[i];
                PianoNote   PNote     = new PianoNote(
                    NoteEvent.AbsoluteTime - off,
                    NoteEvent.NoteLength,
                    new BalthasarLib.PianoRollWindow.PitchValuePair((uint)NoteEvent.NoteNumber, 0)
                    );
                PNote.OctaveType = PitchValuePair.OctaveTypeEnum.Piano;
                PNote.Lyric      = PNote.PitchValue.NoteChar + PNote.PitchValue.Octave.ToString();
                if (PNote.Tick > lastEnd)
                {
                    NoteListEX.Add(new PianoNote(lastEnd, PNote.Tick - lastEnd, 0));
                }
                NoteListEX.Add(PNote);
            }
            using (MidiOut midiOut = new MidiOut(0))
            {
                midiOut.Volume = 65535;
                int  j   = 0;
                int  k   = 0;
                bool isp = false;
                for (int i = 0; i < MidiRecv.Pitchs.Count; i++)
                {
                    if (j >= MidiRecv.Notes.Count)
                    {
                        break;
                    }
                    if (MidiRecv.Pitchs[i].PitchWheelChangeEvent.AbsoluteTime - off < 0)
                    {
                        continue;
                    }
                    if (MidiRecv.Pitchs[i].PitchWheelChangeEvent.AbsoluteTime - off < NoteListEX[j].Tick)
                    {
                        System.Threading.Thread.Sleep((int)tempo.Tick2Millisecond(MidiRecv.Pitchs[i].PitchWheelChangeEvent.DeltaTime));
                        continue;    //在音符前,抛弃
                    }
                    if (MidiRecv.Pitchs[i].PitchWheelChangeEvent.AbsoluteTime - off > NoteListEX[j].Tick + NoteListEX[j].Length)
                    {
                        //在音符后
                        midiOut.Send(MidiMessage.StopNote((int)NoteListEX[j].PitchValue.NoteNumber, 0, 1).RawData);
                        isp = false;
                        j++;
                        k++;
                        i--;    //重来一遍
                        PitchList.Add(k, new List <PitchNode>());
                        continue;
                    }
                    if (!isp)
                    {
                        isp = true;
                        midiOut.Send(MidiMessage.StartNote((int)NoteListEX[j].PitchValue.NoteNumber, 127, 1).RawData);
                    }
                    midiOut.Send(MidiRecv.Pitchs[i].PitchWheelChangeEvent.GetAsShortMessage());
                    System.Threading.Thread.Sleep((int)tempo.Tick2Millisecond(MidiRecv.Pitchs[i].PitchWheelChangeEvent.DeltaTime));
                }
            }
        }
Esempio n. 55
0
        /// <summary>
        /// Sends a MIDI message to the DSMI server
        /// </summary>
        /// <param name="midiMessage">The MIDI message to send</param>
        public static void Send(MidiMessage midiMessage)
        {
            if (!NetworkAvailable)
                return;

            byte[] toSend = BuildMessage(midiMessage.Message, midiMessage.Data1, midiMessage.Data2);

            SocketAsyncEventArgs eventArgs = GetEventArgs(_outEndpoint, toSend);

            eventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
            {
                Debug.WriteLine("DSMI: Midi Message Sent {0} {1} {2}", midiMessage.Message, midiMessage.Data1, midiMessage.Data2);

                _clientDone.Set();
            });

            Socket.ConnectAsync(SocketType.Dgram, ProtocolType.Udp, eventArgs);
        }
Esempio n. 56
0
    void Update()
    {
        // Update the note state array.
        foreach (var cs in channelArray)
        {
            for (var i = 0; i < 128; i++)
            {
                var x = cs.noteArray [i];
                if (x > 1.0f)
                {
                    // Key down -> Hold.
                    cs.noteArray [i] = x - 1.0f;
                }
                else if (x < 0)
                {
                    // Key up -> Off.
                    cs.noteArray [i] = 0.0f;
                }
            }
        }

        // Process the message queue.
        while (true)
        {
            // Pop from the queue.
            var data = DequeueIncomingData();
            if (data == 0)
            {
                break;
            }

            // Parse the message.
            var message = new MidiMessage(data);

            // Split the first byte.
            var statusCode    = message.status >> 4;
            var channelNumber = message.status & 0xf;

            // Note on message?
            if (statusCode == 9)
            {
                var velocity = 1.0f / 127 * message.data2 + 1.0f;
                channelArray [channelNumber].noteArray [message.data1]        = velocity;
                channelArray [(int)MidiChannel.All].noteArray [message.data1] = velocity;
            }

            // Note off message?
            if (statusCode == 8 || (statusCode == 9 && message.data2 == 0))
            {
                channelArray [channelNumber].noteArray [message.data1]        = -1.0f;
                channelArray [(int)MidiChannel.All].noteArray [message.data1] = -1.0f;
            }

            // CC message?
            if (statusCode == 0xb)
            {
                // Normalize the value.
                var value = 1.0f / 127 * message.data2;
                // Update the channel if it already exists, or add a new channel.
                channelArray [channelNumber].knobMap [message.data1] = value;
                // Do again for All-ch.
                channelArray [(int)MidiChannel.All].knobMap [message.data1] = value;
            }

            #if UNITY_EDITOR
            // Record the message history.
            messageHistory.Enqueue(message);
            #endif
        }

        #if UNITY_EDITOR
        // Truncate the history.
        while (messageHistory.Count > 8)
        {
            messageHistory.Dequeue();
        }
        #endif
    }
Esempio n. 57
0
        void Owner_MessageReceived(object sender, MidiMessage message, int channel, int key, int value)
        {
            if (ControlMap != null)
            {
                if (message == MidiMessage.AfterTouch || message == MidiMessage.None)
                {
                    return;
                }
                if (firstMessageReceived)
                {

                    if (ControlMap.ID != key || ControlMap.Channel != channel)
                    {
                        return;
                    }

                    if ( (firstMessage == MidiMessage.NoteOn && message == MidiMessage.NoteOff) || (firstMessage == MidiMessage.NoteOff && message == MidiMessage.NoteOn))
                    {
                        ControlMap.ControlType = ControlType.KeyPress;
                    }
                    else if (firstMessage == MidiMessage.Control && firstValue == 127 && message == MidiMessage.Control && value == 0)
                    {
                        ControlMap.ControlType = ControlType.KeyPress;
                    }
                    else if ((firstMessage == MidiMessage.Control && firstValue == 127 && message == MidiMessage.Control && value == 1)
                            || (firstMessage == MidiMessage.Control && firstValue == 1 && message == MidiMessage.Control && value == 127)
                        || (firstMessage == MidiMessage.Control && firstValue == 1 && message == MidiMessage.Control && value == 1)
                        || (firstMessage == MidiMessage.Control && firstValue == 127 && message == MidiMessage.Control && value == 127)
                        )
                    {

                        ControlMap.ControlType = ControlType.Jog;
                    }
                    else if (message == MidiMessage.Control && ((firstValue < 2 && value < 2)  || (firstValue == 127 && value == 126) || (firstValue > 0 && firstValue < 127 && value > 1 && value < 127)))
                    {
                        ControlMap.ControlType = ControlType.Slider;
                    }

                }
                else
                {
                    firstMessageReceived = true;
                    firstMessage = message;
                    firstValue = value;
                    ControlMap.ID = key;
                    ControlMap.Channel = channel;
                    ControlMap.Name = key.ToString();
                    return;
                }
            }

            MethodInvoker doIt = delegate
            {
                MidiMap.UnhandledMessageReceived -= Owner_MessageReceived;
                EnableControlUi();
            };

            if (InvokeRequired)
            {
                try
                {
                    Invoke(doIt);
                }
                catch
                {
                }
            }
            else
            {
                doIt();
            }
        }
Esempio n. 58
0
		public void OnMidiMessageReceived(MidiMessage msg) {
			this.OnMidiMessage(msg);
		}