2013-10-08 31 views
1

我正在嘗試生成一個音符,它將通過使用Objective-C和MIDI的iPhone揚聲器播放。我有下面的代碼,但它沒有做任何事情。我究竟做錯了什麼?MIDISend:在iPhone上彈奏音符

MIDIPacketList packetList; 

packetList.numPackets = 1; 

MIDIPacket* firstPacket = &packetList.packet[0]; 

firstPacket->timeStamp = 0; // send immediately 

firstPacket->length = 3; 

firstPacket->data[0] = 0x90; 

firstPacket->data[1] = 80; 

firstPacket->data[2] = 120; 

MIDIPacketList pklt=packetList; 

MIDISend(MIDIGetSource(0), MIDIGetDestination(0), &pklt); 

回答

2

你有三個問題:

  1. 聲明一個MIDIPacketList不分配內存或初始化結構
  2. 你傳遞MIDIGetSource(返回MIDIEndpointRef)的結果代替MIDISend的第一個參數代替MIDIPortRef。 (你可能忽略了編譯器的警告,不要忽略編譯器警告。)
  3. 在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);