iOS如何演奏midi音符?

iOS how to play midi notes?

我已经搜索并已经完成了一个可以播放 MIDI 音符的 OS X 应用程序,但是当我在 iOS 中尝试时,没有任何反应。这是核心代码:

AUGraph graph;
AudioUnit synthUnit;
AUNode synthNode, outNode;

NewAUGraph(&graph);

AudioComponentDescription cd;
cd.componentManufacturer = kAudioUnitManufacturer_Apple;

cd.componentType = kAudioUnitType_MusicDevice;
cd.componentSubType = kAudioUnitSubType_MIDISynth;
AUGraphAddNode(graph, &cd, &synthNode);

cd.componentType = kAudioUnitType_Output;
cd.componentSubType = kAudioUnitSubType_GenericOutput;
AUGraphAddNode(graph, &cd, &outNode), "AUGraphAddNode");

CheckError(AUGraphOpen(graph), "AUGraphOpen");

AUGraphConnectNodeInput(graph, synthNode, 0, outNode, 0);

AUGraphNodeInfo(graph, synthNode, 0, &synthUnit);

AUGraphInitialize(graph);
CAShow(graph);

AUGraphStart(graph);

CFURLRef bankURL = ... //gs_instruments.dls
AudioUnitSetProperty(synthUnit,
                    kMusicDeviceProperty_SoundBankURL,
                    kAudioUnitScope_Global,
                    0,
                    &bankURL,
                    sizeof(bankURL));

static UInt32 kChannelMessage_NoteOn = 0x90;
UInt8 channel = 0;
UInt8 note = 60;
UInt32 velocity = 127;

MusicDeviceMIDIEvent(synthUnit,
                    kChannelMessage_NoteOn | channel,
                    note,
                    velocity,
                    0);

AUGraphStop(graph);
DisposeAUGraph(graph);

我知道 cd.componentTypecd.componentSubType 设置可能不正确,因为 iOS 应用程序和 OS X 应用程序之间的区别就是它。在 OS X:

AudioComponentDescription cd;
cd.componentManufacturer = kAudioUnitManufacturer_Apple;

cd.componentType = kAudioUnitType_MusicDevice;
cd.componentSubType = kAudioUnitSubType_DLSSynth;
AUGraphAddNode(graph, &cd, &synthNode);

cd.componentType = kAudioUnitType_Output;
cd.componentSubType = kAudioUnitSubType_DefaultOutput;
AUGraphAddNode(graph, &cd, &outNode);

如何在iOS中设置cd并正确播放MIDI音符?我对 Audio Unit / AUGraph...

没有清楚或深入的了解

更新: 在添加 outNode 时使用 cd.componentSubType = kAudioUnitSubType_RemoteIO; 将是正确的并成功播放软 MIDI 音符。

link 将 AVFoundation 和 AudioToolbox 框架添加到您的项目中,然后使用此代码:

#import <AVFoundation/AVFoundation.h>

NSURL *midiUrl = [[NSBundle mainBundle] URLForResource:@"even voor mij" withExtension:@"mid"];

MusicPlayer player = NULL;

NewMusicPlayer(&player);

MusicSequence sequence = NULL;

NewMusicSequence(&sequence);

MusicSequenceFileLoad(sequence, (__bridge CFURLRef)midiUrl, NULL, NULL);

MusicPlayerSetSequence(player, sequence);

MusicPlayerStart(player);

kAudioUnitSubType_GenericOutput 应该是 kAudioUnitSubType_RemoteIO iOS.

您需要让图表 运行 播放音频,所以不要立即调用 AUGraphStop() 和 DisposeAUGraph()。

为了测试图形,我会使用 kAudioUnitSubType_Sampler 而不是 kAudioUnitSubType_MIDISynth,因为如果你不设置它的预设,它有一个内置的波形发生器。然后当你让图表工作时,试试你的合成器。