你有三個問題:
- 聲明一個
MIDIPacketList
不分配內存或初始化結構
- 你傳遞MIDIGetSource(返回
MIDIEndpointRef
)的結果代替MIDISend
的第一個參數代替MIDIPortRef
。 (你可能忽略了編譯器的警告,不要忽略編譯器警告。)
- 在iOS中發送MIDI音符不會發出任何聲音。如果您沒有連接到iOS設備的外部MIDI設備,則需要使用CoreAudio設置一些可生成聲音的設備。這超出了這個答案的範圍。
所以這個代碼將運行,但它不會使任何聲音,除非你有外部硬件:
//Look to see if there's anything that will actually play MIDI notes
NSLog(@"There are %lu destinations", MIDIGetNumberOfDestinations());
// Prepare MIDI Interface Client/Port for writing MIDI data:
MIDIClientRef midiclient = 0;
MIDIPortRef midiout = 0;
OSStatus status;
status = MIDIClientCreate(CFSTR("Test client"), NULL, NULL, &midiclient);
if (status) {
NSLog(@"Error trying to create MIDI Client structure: %d", (int)status);
}
status = MIDIOutputPortCreate(midiclient, CFSTR("Test port"), &midiout);
if (status) {
NSLog(@"Error trying to create MIDI output port: %d", (int)status);
}
Byte buffer[128];
MIDIPacketList *packetlist = (MIDIPacketList *)buffer;
MIDIPacket *currentpacket = MIDIPacketListInit(packetlist);
NSInteger messageSize = 3; //Note On is a three-byte message
Byte msg[3] = {0x90, 80, 120};
MIDITimeStamp timestamp = 0;
currentpacket = MIDIPacketListAdd(packetlist, sizeof(buffer), currentpacket, timestamp, messageSize, msg);
MIDISend(midiout, MIDIGetDestination(0), packetlist);