Esempio n. 1
0
        //
        //
        //
        public async Task setMidiInputPortId(Windows.Devices.Enumeration.DeviceInformation Di)
        {
            this.midiInputPort = await MidiInPort.FromIdAsync(Di.Id);

            //
            this.midiInputPort.MessageReceived += MidiInputDevice_MessageReceived;
        }
Esempio n. 2
0
        private void MidiInPort_MessageReceived(MidiInPort sender, MidiMessageReceivedEventArgs args)
        {
            IMidiMessage receivedMidiMessage = args.Message;

            System.Diagnostics.Debug.WriteLine(receivedMidiMessage.Timestamp.ToString());

            if (receivedMidiMessage.Type == MidiMessageType.NoteOn)
            {
                byte channel     = ((MidiNoteOnMessage)receivedMidiMessage).Channel;
                byte note        = ((MidiNoteOnMessage)receivedMidiMessage).Note;
                byte velocity    = ((MidiNoteOnMessage)receivedMidiMessage).Velocity;
                int  octave      = note / 12;
                int  fundamental = note % 12;
                System.Diagnostics.Debug.WriteLine(channel);
                System.Diagnostics.Debug.WriteLine(note);
                System.Diagnostics.Debug.WriteLine(velocity);
                System.Diagnostics.Debug.WriteLine(octave);
                System.Diagnostics.Debug.WriteLine(fundamental);


                IMidiMessage message = new MidiNoteOnMessage(channel, note, velocity);
                midiOutPort.SendMessage(message);
            }
            else if (receivedMidiMessage.Type == MidiMessageType.NoteOff)
            {
                byte         channel  = ((MidiNoteOffMessage)receivedMidiMessage).Channel;
                byte         note     = ((MidiNoteOffMessage)receivedMidiMessage).Note;
                byte         velocity = ((MidiNoteOffMessage)receivedMidiMessage).Velocity;
                IMidiMessage message  = new MidiNoteOffMessage(channel, note, velocity);
                midiOutPort.SendMessage(message);
            }
        }
Esempio n. 3
0
        private async void midiInPortListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var deviceInformationCollection = inputDeviceWatcher.DeviceInformationCollection;

            if (deviceInformationCollection == null)
            {
                return;
            }

            DeviceInformation devInfo = deviceInformationCollection[midiInPortListBox.SelectedIndex];

            if (devInfo == null)
            {
                return;
            }

            midiInPort = await MidiInPort.FromIdAsync(devInfo.Id);

            if (midiInPort == null)
            {
                System.Diagnostics.Debug.WriteLine("Unable to create MidiInPort from input device");
                return;
            }
            midiInPort.MessageReceived += MidiInPort_MessageReceived;
        }
Esempio n. 4
0
        public MidiDeviceWatcher(MidiDeviceType ioType, CoreDispatcher dispatcher)
        {
            this.DeviceInformationList = new ObservableCollection <DeviceInformation>();

            m_coreDispatcher = dispatcher;

            switch (ioType)
            {
            case MidiDeviceType.Input:
            {
                m_deviceSelectorString = MidiInPort.GetDeviceSelector();
                break;
            }

            case MidiDeviceType.Output:
            {
                m_deviceSelectorString = MidiOutPort.GetDeviceSelector();
                break;
            }

            default:
            {
                break;
            }
            }

            m_deviceWatcher          = DeviceInformation.CreateWatcher(m_deviceSelectorString);
            m_deviceWatcher.Added   += DeviceWatcher_Added;
            m_deviceWatcher.Removed += DeviceWatcher_Removed;
            m_deviceWatcher.Updated += DeviceWatcher_Updated;
            m_deviceWatcher.EnumerationCompleted += DeviceWatcher_EnumerationCompleted;

            m_deviceType = ioType;
        }
        // using an Initialize method here instead of the constructor in order to
        // prevent a race condition between wiring up the event handlers and
        // finishing enumeration
        public void Initialize()
        {
            ConnectedInputDevices  = new List <MidiDeviceInformation>();
            ConnectedOutputDevices = new List <MidiDeviceInformation>();


            // set up watchers so we know when input devices are added or removed
            _inputWatcher = DeviceInformation.CreateWatcher(MidiInPort.GetDeviceSelector());

            _inputWatcher.EnumerationCompleted += InputWatcher_EnumerationCompleted;
            _inputWatcher.Updated += InputWatcher_Updated;
            _inputWatcher.Removed += InputWatcher_Removed;
            _inputWatcher.Added   += InputWatcher_Added;

            _inputWatcher.Start();

            // set up watcher so we know when output devices are added or removed
            _outputWatcher = DeviceInformation.CreateWatcher(MidiOutPort.GetDeviceSelector());

            _outputWatcher.EnumerationCompleted += OutputWatcher_EnumerationCompleted;
            _outputWatcher.Updated += OutputWatcher_Updated;
            _outputWatcher.Removed += OutputWatcher_Removed;
            _outputWatcher.Added   += OutputWatcher_Added;

            _outputWatcher.Start();
        }
Esempio n. 6
0
        public PianoPage()
        {
            this.InitializeComponent();

            // Setup our device watchers for input and output MIDI devices.
            // Let's us know if devices are connected/disconnected while we're running
            // (And hopefully catches these gracefully so that we don't crash!)
            inputDeviceWatcher = new MidiDeviceWatcher(MidiInPort.GetDeviceSelector(), midiInPortComboBox, Dispatcher);
            inputDeviceWatcher.StartWatcher();

            outputDeviceWatcher = new MidiDeviceWatcher(MidiOutPort.GetDeviceSelector(), midiOutPortComboBox, Dispatcher);
            outputDeviceWatcher.StartWatcher();

            // Helper class to take care of MIDI Control messages, set it up here with the sliders
            msgHelper = new ControlMessageHelper(KB, SliderPitch, SliderMod, SliderVolume, SliderPan, Dispatcher);

            // Register Suspending to clean up any connections we have
            Application.Current.Suspending += Current_Suspending;

            // Register event handlers for KeyTapped and KeyReleased
            // (These events only occur when user taps/clicks on keys on screen)
            KB.K_KeyTapped   += KB_K_KeyTapped;
            KB.K_KeyReleased += KB_K_KeyReleased;

            // Wait until page has finished loading before doing some UI/layout changes
            Loaded += PianoPage_Loaded;
        }
Esempio n. 7
0
        public void MidiInPort_MessageReceived(MidiInPort sender, MidiMessageReceivedEventArgs args)
        {
            IMidiMessage receivedMidiMessage = args.Message;

            rawData         = receivedMidiMessage.RawData.ToArray();
            MessageReceived = true;
        }
        /// <summary>
        /// Constructor.
        /// </summary>
        public MidiController()
        {
            // Get an instance to the event handler and subscribe to the SequencerPositionChanged event.
            this.globalEventHandlerInstance = GlobalEventHandler.GetInstance();

            // Selected MIDI device.
            deviceSelectorString = MidiInPort.GetDeviceSelector();

            // Activate device watcher and add callbacks for state changes.
            deviceWatcher          = DeviceInformation.CreateWatcher(deviceSelectorString);
            deviceWatcher.Added   += DeviceWatcher_Added;
            deviceWatcher.Removed += DeviceWatcher_Removed;
            deviceWatcher.Updated += DeviceWatcher_Updated;
            deviceWatcher.EnumerationCompleted += DeviceWatcher_EnumerationCompleted;

            // Subscribe to changed MIDI device.
            this.globalEventHandlerInstance.SelectedMidiDeviceChanged += this.SelectedMidiDeviceChanged;

            // Subscribe to event to learn MIDI messages.
            this.globalEventHandlerInstance.LearnMidiEvent += this.LearnMidiEvent;

            // Initialize MIDI event triggers.
            for (int i = 0; i < Enum.GetNames(typeof(MidiEventType)).Length; i++)
            {
                learnedMidiTriggers[i] = new MidiEventTrigger();
            }
        }
Esempio n. 9
0
        // Called when app is suspending
        private void Current_Suspending(object sender, Windows.ApplicationModel.SuspendingEventArgs e)
        {
            // Clean up out watchers
            inputDeviceWatcher.StopWatcher();
            inputDeviceWatcher = null;

            outputDeviceWatcher.StopWatcher();
            outputDeviceWatcher = null;

            // Remove EventHandlers and try dispose of input & output ports
            try
            {
                midiInPort.MessageReceived -= MidiInPort_MessageReceived;
                midiInPort.Dispose();
                midiInPort = null;
            }
            catch
            {
            }

            try
            {
                midiOutPort.Dispose();
                midiOutPort = null;
            }
            catch
            {
            }
        }
        /// <summary>
        /// Constructor: Empty device lists, start the device watchers and
        /// set initial states for buttons
        /// </summary>
        public MidiDeviceEnumerationTests()
        {
            InitializeComponent();

            rootGrid.DataContext = this;

            // Start with a clean slate
            ClearAllDeviceValues();

            // Ensure Auto-detect devices toggle is on
            deviceAutoDetectToggle.IsOn = true;

            // Set up the MIDI input and output device watchers
            _midiInDeviceWatcher  = new MidiDeviceWatcher(MidiInPort.GetDeviceSelector(), Dispatcher, inputDevices, InputDevices);
            _midiOutDeviceWatcher = new MidiDeviceWatcher(MidiOutPort.GetDeviceSelector(), Dispatcher, outputDevices, OutputDevices);

            // Start watching for devices
            _midiInDeviceWatcher.Start();
            _midiOutDeviceWatcher.Start();

            // Disable manual enumeration buttons
            listInputDevicesButton.IsEnabled  = false;
            listOutputDevicesButton.IsEnabled = false;

            Unloaded += MidiDeviceEnumerationTests_Unloaded;
        }
Esempio n. 11
0
        private async Task EnumerateDevices()
        {
            var inputDevices = await DeviceInformation.FindAllAsync(MidiInPort.GetDeviceSelector());

            deepMind = null;

            foreach (DeviceInformation device in inputDevices)
            {
                if (device.Name.Contains("DeepMind"))
                {
                    if (deepMind != null)
                    {
                        deepMind.Dispose();
                    }
                    deepMind = await MidiInPort.FromIdAsync(device.Id);

                    this.textBlock.Text = "Captured device!";
                }
            }

            if (deepMind == null)
            {
                return;
            }

            deepMind.MessageReceived += DeepMind_MessageReceived;
        }
Esempio n. 12
0
        public async Task InitInput(String inputDeviceName)
        {
            DeviceInformationCollection midiInputDevices = await DeviceInformation.FindAllAsync(MidiInPort.GetDeviceSelector());

            DeviceInformation midiInDevInfo = null;

            foreach (DeviceInformation device in midiInputDevices)
            {
                if (device.Name.Contains(inputDeviceName) && !device.Name.Contains("CTRL"))
                {
                    midiInDevInfo = device;
                    break;
                }
            }

            if (midiInDevInfo != null)
            {
                midiInPort = await MidiInPort.FromIdAsync(midiInDevInfo.Id);
            }

            if (midiInPort == null)
            {
                System.Diagnostics.Debug.WriteLine("Unable to create MidiInPort from input device");
            }
            else
            {
                midiInPort.MessageReceived += MidiInPort_MessageReceived;
            }
        }
Esempio n. 13
0
        private void MidiInPort_MessageReceived(MidiInPort sender, MidiMessageReceivedEventArgs args)
        {
            IMidiMessage receivedMidiMessage = args.Message;

            byte[] rawData = receivedMidiMessage.RawData.ToArray();
            mainPage.CSignetic6502.MemoryBus.ACIA.MidiInPort_MessageReceived(rawData);
        }
Esempio n. 14
0
        public async Task CreateInput(Device source, Listener acceptor)
        {
            if (source is MidiDevice d)
            {
                var inPort = await MidiInPort.FromIdAsync(d.info.Id);

                inPort.MessageReceived += (sender, args) =>
                {
                    switch (args.Message)
                    {
                    case MidiNoteOnMessage on:
                        acceptor.SendMessage(new NoteOnEvent
                        {
                            Note     = on.Note,
                            Velocity = on.Velocity
                        });
                        break;

                    case MidiNoteOffMessage off:
                        acceptor.SendMessage(new NoteOffEvent
                        {
                            Note     = off.Note,
                            Velocity = off.Velocity
                        });
                        break;
                    }
                };
            }
            else
            {
                throw new ArgumentException("Was given unlisted device");
            }
        }
        protected override async Task ProcessRecordAsync()
        {
            if (!string.IsNullOrWhiteSpace(Id))
            {
                var port = await MidiInPort.FromIdAsync(Id);

                if (port != null)
                {
                    WriteDebug("Acquired input port: " + port.DeviceId);
                }
                else
                {
                    throw new ArgumentException("No input port available with that Id. You can get the Id through the MidiDeviceInformation returned from Get-Midi[Input|Output]DeviceInformation.", "Id");
                }

                // we need to wrap this because PowerShell doesn't understand WinRT/UWP events
                var inputPort = new MidiInputPort(port);

                WriteObject(inputPort);
            }
            else
            {
                throw new ArgumentException("Parameter required. You can get the Id through the MidiDeviceInformation returned from Get-Midi[In|Out]DeviceInformation.", "Id");
            }
        }
Esempio n. 16
0
 internal UwpMidiInput(MidiInPort input, UwpMidiPortDetails details)
 {
     this.input             = input;
     Details                = details;
     Connection             = MidiPortConnectionState.Open;
     input.MessageReceived += DispatchMessageReceived;
 }
        /// <summary>
        /// Process messages received from the Launchpad
        /// </summary>
        /// <param name="sender">Launchpad</param>
        /// <param name="args">Midi Message</param>
        void InPort_MessageReceived(MidiInPort sender, MidiMessageReceivedEventArgs args)
        {
            // Determine what kind of message it is
            switch (args.Message)
            {
            case MidiNoteOnMessage onMessage:     // Grid and side buttons come as Midi Note On Message

                Debug.WriteLine($"Grid ({onMessage.Note % 16}, {(int)(onMessage.Note / 16)}) " + (onMessage.Velocity == 0 ? "Released" : "Pressed"));

                // Get a reference to the button
                var gridButton = gridButtons.FirstOrDefault(button => button.Id == onMessage.Note);

                // If the grid button could not be found (should never happen), return
                if (gridButton == null)
                {
                    return;
                }

                // Update the state (Launchpad sends midi on message for press and release - Velocity 0 is released, 127 is pressed)
                gridButton.State = onMessage.Velocity == 0
                        ? LaunchpadButtonState.Released
                        : LaunchpadButtonState.Pressed;

                // Notify any observable subscribers of the event
                whenButtonStateChanged.OnNext(gridButton);
                break;

            case MidiControlChangeMessage changeMessage:     // Top row comes as Control Change message

                break;
            }
        }
        /// <summary>
        /// Query DeviceInformation class for Midi Input devices
        /// </summary>
        private async Task EnumerateMidiInputDevices()
        {
            // Clear input devices
            InputDevices.Clear();
            InputDeviceProperties.Clear();
            inputDeviceProperties.IsEnabled = false;

            // Find all input MIDI devices
            string midiInputQueryString = MidiInPort.GetDeviceSelector();
            DeviceInformationCollection midiInputDevices = await DeviceInformation.FindAllAsync(midiInputQueryString);

            // Return if no external devices are connected
            if (midiInputDevices.Count == 0)
            {
                InputDevices.Add("No MIDI input devices found!");
                inputDevices.IsEnabled = false;

                NotifyUser("Please connect at least one external MIDI device for this demo to work correctly");
                return;
            }

            // Else, add each connected input device to the list
            foreach (DeviceInformation deviceInfo in midiInputDevices)
            {
                InputDevices.Add(deviceInfo.Name);
                inputDevices.IsEnabled = true;
            }

            NotifyUser("MIDI Input devices found!");
        }
        public SettingsPage()
        {
            this.InitializeComponent();

            inputDeviceWatcher =
                new MidiDeviceWatcher(MidiInPort.GetDeviceSelector(), midiInPortListBox, Dispatcher);

            inputDeviceWatcher.StartWatcher();

            outputDeviceWatcher =
                new MidiDeviceWatcher(MidiOutPort.GetDeviceSelector(), midiOutPortListBox, Dispatcher);

            outputDeviceWatcher.StartWatcher();

            //Set the slider back to the values the user put in
            velocitySlider.Value = (Settings.velocity - 27);
            volumeSlider.Value   = (Settings.volume + 50);
            if (Settings.feedback == true)
            {
                volumeSlider.IsEnabled   = true;
                velocitySlider.IsEnabled = false;
            }
            else
            {
                Feedback.IsChecked       = true;
                volumeSlider.IsEnabled   = false;
                velocitySlider.IsEnabled = true;
            }
        }
 public UwpMidiAccess(Windows.UI.Core.CoreDispatcher dispatcher)
 {
     _midiInDeviceWatcher  = new MidiDeviceWatcher(MidiInPort.GetDeviceSelector(), dispatcher);
     _midiOutDeviceWatcher = new MidiDeviceWatcher(MidiOutPort.GetDeviceSelector(), dispatcher);
     _midiInDeviceWatcher.Start();
     _midiOutDeviceWatcher.Start();
 }
        /// <summary>
        /// The user selected a new MIDI input device.
        /// </summary>
        /// <param name="selectedMidiDeviceIndex">Index of the currently selected MIDI input device as int</param>
        /// <param name="e">PropertyChangedEventArgs</param>
        private async void SelectedMidiDeviceChanged(object selectedMidiDeviceIndex, PropertyChangedEventArgs e)
        {
            // Check that the current list of devices actually contains any devices.
            if ((this.availableMidiDevices == null) || (this.availableMidiDevices.Count < 1))
            {
                return;
            }

            // Check that the currently selected index actually exists in the current list of devices.
            if (this.availableMidiDevices[(int)selectedMidiDeviceIndex] == null)
            {
                return;
            }

            // Get information about the device that was selected.
            DeviceInformation selectedDeviceInfo = this.availableMidiDevices[(int)selectedMidiDeviceIndex];

            // This might fail if the user has selected a device that was disconnected in the mean time.
            if (selectedDeviceInfo == null)
            {
                return;
            }

            // Bind the current MIDI input port to the selected device.
            var midiInPort = await MidiInPort.FromIdAsync(selectedDeviceInfo.Id);

            // This might fail if the device is not accepted as MIDI input source.
            if (midiInPort == null)
            {
                return;
            }

            // Subscribe to receive MIDI messages.
            midiInPort.MessageReceived += MidiMessageReceived;
        }
Esempio n. 22
0
        public MainPage()
        {
            this.InitializeComponent();

            var appView = ApplicationView.GetForCurrentView();

            appView.Title = "";

            // Titlebar
            var coreTitleBar = CoreApplication.GetCurrentView().TitleBar;

            coreTitleBar.ExtendViewIntoTitleBar = false;

            CreateKeyboard();
            CreateSidebar();

            // MIDI
            inputDeviceWatcher =
                new MidiDeviceWatcher(MidiInPort.GetDeviceSelector(), midiInPortListBox, Dispatcher);

            inputDeviceWatcher.StartWatcher();

            outputDeviceWatcher =
                new MidiDeviceWatcher(MidiOutPort.GetDeviceSelector(), midiOutPortListBox, Dispatcher);

            outputDeviceWatcher.StartWatcher();
        }
Esempio n. 23
0
        public async void InputDeviceChanged(Picker DeviceSelector)
        {
            try
            {
                if (!String.IsNullOrEmpty((String)DeviceSelector.SelectedItem))
                {
                    var midiInDeviceInformationCollection = midiInputDeviceWatcher.DeviceInformationCollection;

                    if (midiInDeviceInformationCollection == null)
                    {
                        return;
                    }

                    DeviceInformation midiInDevInfo = midiInDeviceInformationCollection[DeviceSelector.SelectedIndex];

                    if (midiInDevInfo == null)
                    {
                        return;
                    }

                    midiInPort = await MidiInPort.FromIdAsync(midiInDevInfo.Id);

                    if (midiInPort == null)
                    {
                        System.Diagnostics.Debug.WriteLine("Unable to create MidiInPort from input device");
                        return;
                    }
                    midiInPort.MessageReceived += MidiInPort_MessageReceived;
                }
            }
            catch { }
        }
        private async Task LoadInputDevicesAsync()
        {
            WriteDebug("Entering LoadInputDevicesAsync");

            _devices = new List <MidiDeviceInformation>();

            var selector = MidiInPort.GetDeviceSelector();

            WriteDebug("Selector = " + selector);

            var devices = await DeviceInformation.FindAllAsync(selector);

            WriteDebug("Devices count = " + devices.Count);

            foreach (DeviceInformation info in devices)
            {
                WriteDebug("Loading device information into collection " + info.Id);

                var midiDevice = new MidiDeviceInformation();

                midiDevice.Id        = info.Id;
                midiDevice.IsDefault = info.IsDefault;
                midiDevice.IsEnabled = info.IsEnabled;
                midiDevice.Name      = info.Name;

                _devices.Add(midiDevice);
            }

            WriteDebug("Exiting LoadInputDevicesAsync");
        }
Esempio n. 25
0
 public void Start()
 {
     InPort           = new MidiInPort();
     InPort.Successor = new FloppyReceiver();
     InPort.Open(0);
     InPort.Start();
 }
        /// <summary>
        /// Change the input MIDI device from which to receive messages
        /// </summary>
        /// <param name="sender">Element that fired the event</param>
        /// <param name="e">Event arguments</param>
        private async void inputDevices_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // Get the selected input MIDI device
            int selectedInputDeviceIndex = (sender as ListBox).SelectedIndex;

            // Try to create a MidiInPort
            if (selectedInputDeviceIndex < 0)
            {
                // Clear input device messages
                this.inputDeviceMessages.Items.Clear();
                this.inputDeviceMessages.Items.Add("Select a MIDI input device to be able to see its messages");
                this.inputDeviceMessages.IsEnabled = false;
                this.rootPage.NotifyUser("Select a MIDI input device to be able to see its messages", NotifyType.StatusMessage);
                return;
            }

            DeviceInformationCollection devInfoCollection = this.midiInDeviceWatcher.GetDeviceInformationCollection();

            if (devInfoCollection == null)
            {
                this.inputDeviceMessages.Items.Clear();
                this.inputDeviceMessages.Items.Add("Device not found!");
                this.inputDeviceMessages.IsEnabled = false;
                this.rootPage.NotifyUser("Device not found!", NotifyType.ErrorMessage);
                return;
            }

            DeviceInformation devInfo = devInfoCollection[selectedInputDeviceIndex];

            if (devInfo == null)
            {
                this.inputDeviceMessages.Items.Clear();
                this.inputDeviceMessages.Items.Add("Device not found!");
                this.inputDeviceMessages.IsEnabled = false;
                this.rootPage.NotifyUser("Device not found!", NotifyType.ErrorMessage);
                return;
            }

            var currentMidiInputDevice = await MidiInPort.FromIdAsync(devInfo.Id);

            if (currentMidiInputDevice == null)
            {
                this.rootPage.NotifyUser("Unable to create MidiInPort from input device", NotifyType.ErrorMessage);
                return;
            }

            // We have successfully created a MidiInPort; add the device to the list of active devices, and set up message receiving
            if (!this.midiInPorts.Contains(currentMidiInputDevice))
            {
                this.midiInPorts.Add(currentMidiInputDevice);
                currentMidiInputDevice.MessageReceived += MidiInputDevice_MessageReceived;
            }

            // Clear any previous input messages
            this.inputDeviceMessages.Items.Clear();
            this.inputDeviceMessages.IsEnabled = true;

            this.rootPage.NotifyUser("Input Device selected successfully! Waiting for messages...", NotifyType.StatusMessage);
        }
Esempio n. 27
0
 public MidiReceiver(AppData appData)
 {
     _appData = appData;
     _inPort  = new MidiInPort
     {
         Successor = this
     };
 }
Esempio n. 28
0
        private static async Task <List <MidiInDevice> > _GetAllDevices(bool returnEmptyNames = false)
        {
            var midiInputQueryString = MidiInPort.GetDeviceSelector();
            var midiInputDevices     = await DeviceInformation.FindAllAsync(midiInputQueryString);

            return((from device in midiInputDevices where returnEmptyNames || device.Name.Length != 0
                    select new MidiInDevice(device)).ToList());
        }
Esempio n. 29
0
 public MIDIListener(MidiInPort midiInPort)
 {
     this.midiInPort = midiInPort;
     this.midiInPort.MessageReceived += MidiInPort_MessageRecieved;
     dispatcher.Interval              = new TimeSpan(50);
     dispatcher.Tick += Monitor;
     dispatcher.Start();
 }
Esempio n. 30
0
        void DispatchMessageReceived(MidiInPort port, MidiMessageReceivedEventArgs args)
        {
            var data = args.Message.RawData.ToArray();

            MessageReceived(this, new MidiReceivedEventArgs {
                Data = data, Start = 0, Length = data.Length, Timestamp = (long)args.Message.Timestamp.TotalMilliseconds
            });
        }
        public MidiInputPort(MidiInPort port)
        {
            RawPort = port;

            TranslateZeroVelocityNoteOnMessage = true;

            FilterMode = MidiFilterMode.Inactive;

            RawPort.MessageReceived += OnMidiMessageReceived;
        }
Esempio n. 32
0
        public Form1()
        {
            InitializeComponent();
            small = GetIcon(ShellIconSize.SmallIcon);
            large = GetIcon(ShellIconSize.LargeIcon);
            //set normal icons
            SendMessage(this.Handle, WM_SETICON, SHGFI_LARGEICON, small.Handle);
            SendMessage(this.Handle, WM_SETICON, SHGFI_SMALLICON, large.Handle);

            //fully hide window but at least load it
            this.WindowState = FormWindowState.Minimized;
            this.ShowInTaskbar = false;

            trayMenu = new ContextMenu();
            trayMenu.MenuItems.Add("Exit", trayIcon_Close);

            trayIcon = new NotifyIcon();
            trayIcon.Text = this.Text;
            if (SystemInformation.SmallIconSize.Width == 16 && SystemInformation.SmallIconSize.Height == 16) //get 16x16
                trayIcon.Icon = new Icon(small, SystemInformation.SmallIconSize);
            else //just calculate from base 32x32 icon to (hopefully) look better
                trayIcon.Icon = new Icon(large, SystemInformation.SmallIconSize);

            // Add menu to tray icon and show it.
            trayIcon.ContextMenu = trayMenu;
            trayIcon.Visible = true;
            trayIcon.MouseClick += trayIcon_MouseClick;

            devInBox.DropDownStyle = ComboBoxStyle.DropDownList;
            devOutBox.DropDownStyle = ComboBoxStyle.DropDownList;
            
            inDevs = new List<int>();
            outDevs = new List<int>();
            mahPort = new TeVirtualMIDI(pString);
            inPort = new MidiInPort();
            outPort = new MidiOutPort();
            pthrough = new Thread(new ThreadStart(readInput));
            config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            inPort.Successor = new MyReceiver();

            this.Load += onLoad;
            this.FormClosed += onClosed;
            this.Resize += onResize;
        }
        private async void Page_Loaded(object sender, RoutedEventArgs e)
        {
            // midi

            var s = MidiInPort.GetDeviceSelector();
            var information = await DeviceInformation.FindAllAsync(s);

            var list = information.ToList();
            port = await MidiInPort.FromIdAsync(list.ElementAt(2).Id);
            port.MessageReceived += Port_MessageReceived;

            // audio
            var settings = new AudioGraphSettings(AudioRenderCategory.GameEffects);
            settings.QuantumSizeSelectionMode = QuantumSizeSelectionMode.LowestLatency;
            var creation = await AudioGraph.CreateAsync(settings);

            graph = creation.Graph;
            output = await graph.CreateDeviceOutputNodeAsync();

            var encoding = graph.EncodingProperties;
            encoding.ChannelCount = 1;
            input = graph.CreateFrameInputNode(encoding);
            input.AddOutgoingConnection(output.DeviceOutputNode);
            input.Stop();

            input.QuantumStarted += Input_QuantumStarted;

            graph.Start();

            // midi notes (pitch to note)

            float a = 440; // a is 440 hz...
            for (int x = 0; x < 127; ++x)
            {
                notes[x] = (a / 32f) * (float)Math.Pow(2f, ((x - 9f) / 12f));
            }
        }
        private void Port_MessageReceived(MidiInPort sender, MidiMessageReceivedEventArgs args)
        {
            if (args.Message.Type == MidiMessageType.NoteOn)
            {
                var msg = (MidiNoteOnMessage)args.Message;

                if (msg.Note != 0)
                {
                    view.Title = $"Pitch: {msg.Note}, Velocity: {msg.Velocity}";

                    if (msg.Velocity != 0)
                    {
                        notesPlaying++;

                        freq = notes[msg.Note];
                        theta = 0;

                        input.Start();
                    }
                    else
                    {
                        notesPlaying--;

                        if (notesPlaying == 0)
                            input.Stop();
                    }
                }
            }
        }
 public MidiInPortEvents(MidiInPort This)
 {
     this.This = This;
 }
        /// <summary>
        /// Display the received MIDI message in a readable format
        /// </summary>
        /// <param name="sender">Element that fired the event</param>
        /// <param name="args">The received message</param>
        private async void MidiInputDevice_MessageReceived(MidiInPort sender, MidiMessageReceivedEventArgs args)
        {
            IMidiMessage receivedMidiMessage = args.Message;

            // Build the received MIDI message into a readable format
            StringBuilder outputMessage = new StringBuilder();
            outputMessage.Append(receivedMidiMessage.Timestamp.ToString()).Append(", Type: ").Append(receivedMidiMessage.Type);

            // Add MIDI message parameters to the output, depending on the type of message
            switch (receivedMidiMessage.Type)
            {
                case MidiMessageType.NoteOff:
                    var noteOffMessage = (MidiNoteOffMessage)receivedMidiMessage;
                    outputMessage.Append(", Channel: ").Append(noteOffMessage.Channel).Append(", Note: ").Append(noteOffMessage.Note).Append(", Velocity: ").Append(noteOffMessage.Velocity);
                    break;
                case MidiMessageType.NoteOn:
                    var noteOnMessage = (MidiNoteOnMessage)receivedMidiMessage;
                    outputMessage.Append(", Channel: ").Append(noteOnMessage.Channel).Append(", Note: ").Append(noteOnMessage.Note).Append(", Velocity: ").Append(noteOnMessage.Velocity);
                    break;
                case MidiMessageType.PolyphonicKeyPressure:
                    var polyphonicKeyPressureMessage = (MidiPolyphonicKeyPressureMessage)receivedMidiMessage;
                    outputMessage.Append(", Channel: ").Append(polyphonicKeyPressureMessage.Channel).Append(", Note: ").Append(polyphonicKeyPressureMessage.Note).Append(", Pressure: ").Append(polyphonicKeyPressureMessage.Pressure);
                    break;
                case MidiMessageType.ControlChange:
                    var controlChangeMessage = (MidiControlChangeMessage)receivedMidiMessage;
                    outputMessage.Append(", Channel: ").Append(controlChangeMessage.Channel).Append(", Controller: ").Append(controlChangeMessage.Controller).Append(", Value: ").Append(controlChangeMessage.ControlValue);
                    break;
                case MidiMessageType.ProgramChange:
                    var programChangeMessage = (MidiProgramChangeMessage)receivedMidiMessage;
                    outputMessage.Append(", Channel: ").Append(programChangeMessage.Channel).Append(", Program: ").Append(programChangeMessage.Program);
                    break;
                case MidiMessageType.ChannelPressure:
                    var channelPressureMessage = (MidiChannelPressureMessage)receivedMidiMessage;
                    outputMessage.Append(", Channel: ").Append(channelPressureMessage.Channel).Append(", Pressure: ").Append(channelPressureMessage.Pressure);
                    break;
                case MidiMessageType.PitchBendChange:
                    var pitchBendChangeMessage = (MidiPitchBendChangeMessage)receivedMidiMessage;
                    outputMessage.Append(", Channel: ").Append(pitchBendChangeMessage.Channel).Append(", Bend: ").Append(pitchBendChangeMessage.Bend);
                    break;
                case MidiMessageType.SystemExclusive:
                    var systemExclusiveMessage = (MidiSystemExclusiveMessage)receivedMidiMessage;
                    outputMessage.Append(", ");

                    // Read the SysEx bufffer
                    var sysExDataReader = DataReader.FromBuffer(systemExclusiveMessage.RawData);
                    while (sysExDataReader.UnconsumedBufferLength > 0)
                    {
                        byte byteRead = sysExDataReader.ReadByte();
                        // Pad with leading zero if necessary
                        outputMessage.Append(byteRead.ToString("X2")).Append(" ");
                    }
                    break;
                case MidiMessageType.MidiTimeCode:
                    var timeCodeMessage = (MidiTimeCodeMessage)receivedMidiMessage;
                    outputMessage.Append(", FrameType: ").Append(timeCodeMessage.FrameType).Append(", Values: ").Append(timeCodeMessage.Values);
                    break;
                case MidiMessageType.SongPositionPointer:
                    var songPositionPointerMessage = (MidiSongPositionPointerMessage)receivedMidiMessage;
                    outputMessage.Append(", Beats: ").Append(songPositionPointerMessage.Beats);
                    break;
                case MidiMessageType.SongSelect:
                    var songSelectMessage = (MidiSongSelectMessage)receivedMidiMessage;
                    outputMessage.Append(", Song: ").Append(songSelectMessage.Song);
                    break;
                case MidiMessageType.TuneRequest:
                    var tuneRequestMessage = (MidiTuneRequestMessage)receivedMidiMessage;
                    break;
                case MidiMessageType.TimingClock:
                    var timingClockMessage = (MidiTimingClockMessage)receivedMidiMessage;
                    break;
                case MidiMessageType.Start:
                    var startMessage = (MidiStartMessage)receivedMidiMessage;
                    break;
                case MidiMessageType.Continue:
                    var continueMessage = (MidiContinueMessage)receivedMidiMessage;
                    break;
                case MidiMessageType.Stop:
                    var stopMessage = (MidiStopMessage)receivedMidiMessage;
                    break;
                case MidiMessageType.ActiveSensing:
                    var activeSensingMessage = (MidiActiveSensingMessage)receivedMidiMessage;
                    break;
                case MidiMessageType.SystemReset:
                    var systemResetMessage = (MidiSystemResetMessage)receivedMidiMessage;
                    break;
                case MidiMessageType.None:
                    throw new InvalidOperationException();
                default:
                    break;
            }

            // Use the Dispatcher to update the messages on the UI thread
            await Dispatcher.RunAsync(CoreDispatcherPriority.High, () =>
            {
                // Skip TimingClock and ActiveSensing messages to avoid overcrowding the list. Commment this check out to see all messages
                if ((receivedMidiMessage.Type != MidiMessageType.TimingClock) && (receivedMidiMessage.Type != MidiMessageType.ActiveSensing))
                {
                    this.inputDeviceMessages.Items.Add(outputMessage + "\n");
                    this.inputDeviceMessages.ScrollIntoView(this.inputDeviceMessages.Items[this.inputDeviceMessages.Items.Count - 1]);
                    this.rootPage.NotifyUser("Message received successfully!", NotifyType.StatusMessage);
                }
            });
        }
        private void OnMidiMessageReceived(MidiInPort sender, MidiMessageReceivedEventArgs args)
        {
            // Console.WriteLine("OnMidiMessageReceived: " + args.Message.Type);

            switch (args.Message.Type)
            {
                case MidiMessageType.NoteOn:
                    var noteOnMessage = args.Message as MidiNoteOnMessage;

                    // a zero-velocity note-on message is equivalent to note-off
                    if (noteOnMessage.Velocity == 0 && TranslateZeroVelocityNoteOnMessage)
                    {
                        var ev1 = NoteOffMessageReceived;
                        if (ev1 != null)
                            ev1(this, new MidiNoteOffMessageReceivedEventArgs(noteOnMessage.Channel, noteOnMessage.Note, noteOnMessage.Velocity, true));
                    }
                    else
                    {
                        // normal note on message
                        var ev2 = NoteOnMessageReceived;
                        if (ev2 != null)
                        {
                            try
                            {
                                ev2(this, new MidiNoteOnMessageReceivedEventArgs(noteOnMessage.Channel, noteOnMessage.Note, noteOnMessage.Velocity));
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(ex.ToString());
                            }
                        }
                    }

                    break;

                case MidiMessageType.NoteOff:
                    var noteOffMessage = args.Message as MidiNoteOffMessage;
                    var ev3 = NoteOffMessageReceived;
                    if (ev3 != null)
                        ev3(this, new MidiNoteOffMessageReceivedEventArgs(noteOffMessage.Channel, noteOffMessage.Note, noteOffMessage.Velocity, false));
                    break;

                case MidiMessageType.ControlChange:
                    var ccMessage = args.Message as MidiControlChangeMessage;
                    var ev4 = ControlChangeMessageReceived;
                    if (ev4 != null)
                        ev4(this, new MidiControlChangeMessageReceivedEventArgs(ccMessage.Channel, ccMessage.Controller, ccMessage.ControlValue));
                    break;

                case MidiMessageType.ProgramChange:
                    var programMessage = args.Message as MidiProgramChangeMessage;
                    var ev5 = ProgramChangeMessageReceived;
                    if (ev5 != null)
                        ev5(this, new MidiProgramChangeMessageReceivedEventArgs(programMessage.Channel, programMessage.Program));
                    break;

                case MidiMessageType.PitchBendChange:
                    var pitchBendChangeMessage = args.Message as MidiPitchBendChangeMessage;
                    var ev6 = PitchBendChangeMessageReceived;
                    if (ev6 != null)
                        ev6(this, new MidiPitchBendChangeMessageReceivedEventArgs(pitchBendChangeMessage.Channel,  pitchBendChangeMessage.Bend));
                    break;

                // TODO: Add more message types

                default:
                    // message type we don't handle above. Ignore
                    break;
            }
        }