bool midi_init(void) { OSStatus result; result = CreateAUGraph(); if (result != 0) return false; result = AUGraphInitialize(s_graph); if (result != 0) return false; result = AUGraphStart(s_graph); if (result != 0) return false; return true; }
int main (int argc, const char * argv[]) { AUGraph graph = 0; AudioUnit synthUnit; OSStatus result; char* bankPath = 0; UInt8 midiChannelInUse = 0; //we're using midi channel 1... // this is the only option to main that we have... // just the full path of the sample bank... // On OS X there are known places were sample banks can be stored // Library/Audio/Sounds/Banks - so you could scan this directory and give the user options // about which sample bank to use... if (argc > 1) bankPath = const_cast<char*>(argv[1]); require_noerr (result = CreateAUGraph (graph, synthUnit), home); // if the user supplies a sound bank, we'll set that before we initialize and start playing if (bankPath) { FSSpec soundBankSpec; require_noerr (result = PathToFSSpec (bankPath, soundBankSpec), home); printf ("Setting Sound Bank:%s\n", bankPath); require_noerr (result = AudioUnitSetProperty (synthUnit, kMusicDeviceProperty_SoundBankFSSpec, kAudioUnitScope_Global, 0, &soundBankSpec, sizeof(soundBankSpec)), home); } // ok we're set up to go - initialize and start the graph require_noerr (result = AUGraphInitialize (graph), home); //set our bank require_noerr (result = MusicDeviceMIDIEvent(synthUnit, kMidiMessage_ControlChange << 4 | midiChannelInUse, kMidiMessage_BankMSBControl, 0, 0/*sample offset*/), home); require_noerr (result = MusicDeviceMIDIEvent(synthUnit, kMidiMessage_ProgramChange << 4 | midiChannelInUse, 0/*prog change num*/, 0, 0/*sample offset*/), home); CAShow (graph); // prints out the graph so we can see what it looks like... require_noerr (result = AUGraphStart (graph), home); // we're going to play an octave of MIDI notes: one a second for (int i = 0; i < 13; i++) { UInt32 noteNum = i + 60; UInt32 onVelocity = 127; UInt32 noteOnCommand = kMidiMessage_NoteOn << 4 | midiChannelInUse; printf ("Playing Note: Status: 0x%lX, Note: %ld, Vel: %ld\n", noteOnCommand, noteNum, onVelocity); require_noerr (result = MusicDeviceMIDIEvent(synthUnit, noteOnCommand, noteNum, onVelocity, 0), home); // sleep for a second usleep (1 * 1000 * 1000); require_noerr (result = MusicDeviceMIDIEvent(synthUnit, noteOnCommand, noteNum, 0, 0), home); } // ok we're done now home: if (graph) { AUGraphStop (graph); // stop playback - AUGraphDispose will do that for us but just showing you what to do DisposeAUGraph (graph); } return result; }