1

我正在尝试使用 Objective-C 和 MIDI 生成将通过 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);
4

1 回答 1

2

你有三个问题:

  1. 声明 aMIDIPacketList不会分配内存或初始化结构
  2. 您将 MIDIGetSource (返回 a MIDIEndpointRef)的结果作为第一个参数传递到MIDISend它期望 a 的位置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);
于 2013-10-08T20:01:22.950 回答