CoreMIDI MIDIInputPortCreateWithProtocol problem with more than 2 keys pressed

168 views Asked by At

I'm studying CoreMIDI to connect a musical keyboard to get keys pressed and mount chord.

After few days I don't know why sometimes the block from MIDIInputPortCreateWithProtocol not receive some events.

For example:

  • If I press one key an release it, the events received normally.
  • If I press two keys simultaneously sometimes I receive two events with one packet in each one or receive one event with two packets, but sometimes one key event pressed not reach the block, registering just one key pressed or released.
  • If I press three key normally one event or one packet from one key not reach the block

But when I press one key separately and not release it I receive all keys pressed.

My MIDIInputPortCreateWithProtocol code is

func createInputPort(midiClient: MIDIClientRef) {
        MIDIInputPortCreateWithProtocol(midiClient, "Input Port" as CFString, MIDIProtocolID._1_0, &self.inputPort) {  [weak self] eventList, srcConnRefCon in
            print("=== event received")

            guard let strogSelf = self else {
                return
            }
            
            let midiEventList: MIDIEventList = eventList.pointee
            var packet = midiEventList.packet
            
            for _ in 1...midiEventList.numPackets {
                let words = Mirror(reflecting: packet.words).children
                for word in words {
                    guard let uint32 = word.value as? UInt32,
                          uint32 > 0 else { return }
                    
                    let messageType = (uint32 & 0xF0000000) >> 28
                    
                    if (messageType == 0x02) {
                        let status = (uint32 & 0x00FF0000) >> 16
                        let midiCommand = status >> 4                        
                        if midiCommand == strogSelf.NOTE_ON {
                            strogSelf.noteAdd(noteInfo: MidiPacket(data: uint32, command: midiCommand, timeStamp: packet.timeStamp))
                            break
                        } else if midiCommand == strogSelf.NOTE_OFF {
                            strogSelf.noteRemove(noteInfo: MidiPacket(data: uint32, command: midiCommand, timeStamp: packet.timeStamp))
                            break
                        }
                    }
                }
                packet = MIDIEventPacketNext(&packet).pointee
            }
        }
        
        MIDIPortConnectSource(self.inputPort, self.endpoint ?? MIDIGetSource(MIDIGetNumberOfSources()-1), &self.connRefCon)
}

The ideia is receive all key pressed like in garageband.

If I open garageband together with my project, when I press three keys simultaneously the garage band detect all of them and my project sometimes not.

Anyone have some ideia what is happen here?

Thanks a lot

0

There are 0 answers