Allegro.cc - Online Community

Allegro.cc Forums » Programming Questions » MIDI Out on Mac, simple code needed

This thread is locked; no one can reply to it. rss feed Print
MIDI Out on Mac, simple code needed
aj5555
Member #9,033
September 2007

I need to send a midi string out a MIDI interface on a Mac.
I need a simple standalone program that i can run, passing the hex bytes to send out the midi interface.
I haven't got a mac that i can write code upon, so im looking for someone that could write such a thing or be able to give me the information i'd need to persue this... any help would be greatly appreciated.

Thomas Harte
Member #33
April 2000
avatar

CoreAudio has a CoreMIDI component. I'm clueless about MIDI, does the following example that comes with the Developer Tools help?

1/* Copyright © 2007 Apple Inc. All Rights Reserved.
2
3 Disclaimer: IMPORTANT: This Apple software is supplied to you by
4 Apple Inc. ("Apple") in consideration of your agreement to the
5 following terms, and your use, installation, modification or
6 redistribution of this Apple software constitutes acceptance of these
7 terms. If you do not agree with these terms, please do not use,
8 install, modify or redistribute this Apple software.
9
10 In consideration of your agreement to abide by the following terms, and
11 subject to these terms, Apple grants you a personal, non-exclusive
12 license, under Apple's copyrights in this original Apple software (the
13 "Apple Software"), to use, reproduce, modify and redistribute the Apple
14 Software, with or without modifications, in source and/or binary forms;
15 provided that if you redistribute the Apple Software in its entirety and
16 without modifications, you must retain this notice and the following
17 text and disclaimers in all such redistributions of the Apple Software.
18 Neither the name, trademarks, service marks or logos of Apple Inc.
19 may be used to endorse or promote products derived from the Apple
20 Software without specific prior written permission from Apple. Except
21 as expressly stated in this notice, no other rights or licenses, express
22 or implied, are granted by Apple herein, including but not limited to
23 any patent rights that may be infringed by your derivative works or by
24 other works in which the Apple Software may be incorporated.
25
26 The Apple Software is provided by Apple on an "AS IS" basis. APPLE
27 MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
28 THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS
29 FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND
30 OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
31
32 IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
33 OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
34 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
35 INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION,
36 MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED
37 AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
38 STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
39 POSSIBILITY OF SUCH DAMAGE.
40*/
41#include <CoreMIDI/MIDIServices.h>
42#include <CoreFoundation/CFRunLoop.h>
43#include <stdio.h>
44 
45// ___________________________________________________________________________________________
46// test program to echo MIDI In to Out
47// ___________________________________________________________________________________________
48 
49MIDIPortRef gOutPort = NULL;
50MIDIEndpointRef gDest = NULL;
51int gChannel = 0;
52 
53static void MyReadProc(const MIDIPacketList *pktlist, void *refCon, void *connRefCon)
54{
55 if (gOutPort != NULL && gDest != NULL) {
56 MIDIPacket *packet = (MIDIPacket *)pktlist->packet; // remove const (!)
57 for (unsigned int j = 0; j < pktlist->numPackets; ++j) {
58 for (int i = 0; i < packet->length; ++i) {
59// printf("%02X ", packet->data<i>);
60 
61 // rechannelize status bytes
62 if (packet->data<i> >= 0x80 && packet->data<i> < 0xF0)
63 packet->data<i> = (packet->data<i> & 0xF0) | gChannel;
64 }
65 
66// printf("\n");
67 packet = MIDIPacketNext(packet);
68 }
69 
70 MIDISend(gOutPort, gDest, pktlist);
71 }
72}
73 
74int main(int argc, char *argv[])
75{
76 if (argc >= 2) {
77 // first argument, if present, is the MIDI channel number to echo to (1-16)
78 sscanf(argv[1], "%d", &gChannel);
79 if (gChannel < 1) gChannel = 1;
80 else if (gChannel > 16) gChannel = 16;
81 --gChannel; // convert to 0-15
82 }
83 
84 // create client and ports
85 MIDIClientRef client = NULL;
86 MIDIClientCreate(CFSTR("MIDI Echo"), NULL, NULL, &client);
87
88 MIDIPortRef inPort = NULL;
89 MIDIInputPortCreate(client, CFSTR("Input port"), MyReadProc, NULL, &inPort);
90 MIDIOutputPortCreate(client, CFSTR("Output port"), &gOutPort);
91
92 // enumerate devices (not really related to purpose of the echo program
93 // but shows how to get information about devices)
94 int i, n;
95 CFStringRef pname, pmanuf, pmodel;
96 char name[64], manuf[64], model[64];
97
98 n = MIDIGetNumberOfDevices();
99 for (i = 0; i < n; ++i) {
100 MIDIDeviceRef dev = MIDIGetDevice(i);
101
102 MIDIObjectGetStringProperty(dev, kMIDIPropertyName, &pname);
103 MIDIObjectGetStringProperty(dev, kMIDIPropertyManufacturer, &pmanuf);
104 MIDIObjectGetStringProperty(dev, kMIDIPropertyModel, &pmodel);
105
106 CFStringGetCString(pname, name, sizeof(name), 0);
107 CFStringGetCString(pmanuf, manuf, sizeof(manuf), 0);
108 CFStringGetCString(pmodel, model, sizeof(model), 0);
109 CFRelease(pname);
110 CFRelease(pmanuf);
111 CFRelease(pmodel);
112 
113 printf("name=%s, manuf=%s, model=%s\n", name, manuf, model);
114 }
115
116 // open connections from all sources
117 n = MIDIGetNumberOfSources();
118 printf("%d sources\n", n);
119 for (i = 0; i < n; ++i) {
120 MIDIEndpointRef src = MIDIGetSource(i);
121 MIDIPortConnectSource(inPort, src, NULL);
122 }
123
124 // find the first destination
125 n = MIDIGetNumberOfDestinations();
126 if (n > 0)
127 gDest = MIDIGetDestination(0);
128 
129 if (gDest != NULL) {
130 MIDIObjectGetStringProperty(gDest, kMIDIPropertyName, &pname);
131 CFStringGetCString(pname, name, sizeof(name), 0);
132 CFRelease(pname);
133 printf("Echoing to channel %d of %s\n", gChannel + 1, name);
134 } else {
135 printf("No MIDI destinations present\n");
136 }
137 
138 CFRunLoopRun();
139 // run until aborted with control-C
140 
141 return 0;
142}

I guess the relevant bits are:
MIDIOutputPortCreate(client, CFSTR("Output port"), &gOutPort);
To create an outgoing port,
gDest = MIDIGetDestination(0);
To pick a MIDI destination and the MIDIPacket and MIDIPacketList structs:

1/*!
2 @struct MIDIPacket
3 @abstract A collection of simultaneous MIDI events.
4
5 @field timeStamp
6 The time at which the events occurred, if receiving MIDI,
7 or, if sending MIDI, the time at which the events are to
8 be played. Zero means "now." The time stamp applies
9 to the first MIDI byte in the packet.
10 @field length
11 The number of valid MIDI bytes which follow, in data. (It
12 may be larger than 256 bytes if the packet is dynamically
13 allocated.)
14 @field data
15 A variable-length stream of MIDI messages. Running status
16 is not allowed. In the case of system-exclusive
17 messages, a packet may only contain a single message, or
18 portion of one, with no other MIDI events.
19
20 The MIDI messages in the packet must always be complete,
21 except for system-exclusive.
22
23 (This is declared to be 256 bytes in length so clients
24 don't have to create custom data structures in simple
25 situations.)
26*/
27struct MIDIPacket
28{
29 MIDITimeStamp timeStamp;
30 UInt16 length;
31 Byte data[256];
32};
33 
34typedef struct MIDIPacket MIDIPacket;/*!
35 @struct MIDIPacketList
36 @abstract A list of MIDI events being received from, or being sent to,
37 one endpoint.
38 @discussion
39 The timestamps in the packet list must be in ascending order.
40
41 Note that the packets in the list, while defined as an array, may not be
42 accessed as an array, since they are variable-length. To iterate through
43 the packets in a packet list, use a loop such as:
44<pre>
45@textblock
46 MIDIPacket *packet = &packetList->packet[0];
47 for (int i = 0; i < packetList->numPackets; ++i) {
48 ...
49 packet = MIDIPacketNext(packet);
50 }
51@/textblock
52</pre>
53
54 @field numPackets
55 The number of MIDIPackets in the list.
56 @field packet
57 An open-ended array of variable-length MIDIPackets.
58*/
59struct MIDIPacketList
60{
61 UInt32 numPackets;
62 MIDIPacket packet[1];
63};

With those, just use MIDISend(MIDIPortRef port, MIDIEndpointRef dest, const MIDIPacketList *pktlist).

EDIT: if you can send me a meaningful hex byte list then I can try to knock up a commandline program for you. At the minute I don't really know enough about MIDI to be able to do anything on my own.

[My site [members.allegro.cc]] [Tetrominoes [members.allegro.cc]]

aj5555
Member #9,033
September 2007

thats awesome!
thanks for the info.
i dont have access to a Mac for another week.
I'd love to see a simple commandline app.

It needs to
1. connect to the midiout adapter
2. send the bytes from the commandline
3. exit

thats exactly what i need.

what i want to send is a Program Change message.
eg. bin-> 1100nnnn 0ppppppp Program change
in hex.. 0xCn 0x7F where n is channel, for my purposes it could be hard coded to channel 1 hex=0x00 so the complete message to send is 2 bytes.

uint8_t bytes_to_send[2];
bytes_to_send[0] = 0xC0;
bytes_to_send[0] = 0x7f & atoi(argv[1]);

reference: http://www.midi.org/about-midi/table1.shtml

does that make sense?

Thomas Harte
Member #33
April 2000
avatar

Cool — my main concern is that while it'll be easy enough to write something that compiles and superficially appears to be throwing bytes at an output device, I've not really enough knowledge to be able to test what I'm doing. But if you'll have a Mac in a week anyway, then I guess you'll be able to do that bit yourself. I'll do some hasty work on the Apple demo program and post to this thread or edit this post as necessary in the next couple of days...

EDIT:
Does this do what you want? Time will tell...

1#include <CoreServices/CoreServices.h> //for file stuff
2#include <AudioUnit/AudioUnit.h>
3#include <AudioToolbox/AudioToolbox.h> //for AUGraph
4#include <unistd.h> // used for usleep...
5 
6// This call creates the Graph and the Synth unit...
7OSStatus CreateAUGraph (AUGraph &outGraph, AudioUnit &outSynth)
8{
9 OSStatus result;
10 //create the nodes of the graph
11 AUNode synthNode, limiterNode, outNode;
12
13 ComponentDescription cd;
14 cd.componentManufacturer = kAudioUnitManufacturer_Apple;
15 cd.componentFlags = 0;
16 cd.componentFlagsMask = 0;
17 
18 require_noerr (result = NewAUGraph (&outGraph), home);
19 
20 cd.componentType = kAudioUnitType_MusicDevice;
21 cd.componentSubType = kAudioUnitSubType_DLSSynth;
22 
23 require_noerr (result = AUGraphAddNode (outGraph, &cd, &synthNode), home);
24 
25 cd.componentType = kAudioUnitType_Effect;
26 cd.componentSubType = kAudioUnitSubType_PeakLimiter;
27 
28 require_noerr (result = AUGraphAddNode (outGraph, &cd, &limiterNode), home);
29 
30 cd.componentType = kAudioUnitType_Output;
31 cd.componentSubType = kAudioUnitSubType_DefaultOutput;
32 require_noerr (result = AUGraphAddNode (outGraph, &cd, &outNode), home);
33
34 require_noerr (result = AUGraphOpen (outGraph), home);
35
36 require_noerr (result = AUGraphConnectNodeInput (outGraph, synthNode, 0, limiterNode, 0), home);
37 require_noerr (result = AUGraphConnectNodeInput (outGraph, limiterNode, 0, outNode, 0), home);
38
39 // ok we're good to go - get the Synth Unit...
40 require_noerr (result = AUGraphNodeInfo(outGraph, synthNode, 0, &outSynth), home);
41 
42home:
43 return result;
44}
45 
46 
47// some MIDI constants:
48enum {
49 kMidiMessage_ControlChange = 0xB,
50 kMidiMessage_ProgramChange = 0xC,
51 kMidiMessage_BankMSBControl = 0,
52 kMidiMessage_BankLSBControl = 32,
53 kMidiMessage_NoteOn = 0x9
54};
55 
56int main (int argc, const char * argv[]) {
57 AUGraph graph = 0;
58 AudioUnit synthUnit;
59 OSStatus result;
60 unsigned char *Buffer;
61 int BufferLen;
62 
63 if (argc < 2)
64 {
65 printf("No input!\n");
66 exit(1);
67 }
68 else
69 {
70 if(strlen(argv[1])&1)
71 {
72 printf("odd number of input characters\n");
73 exit(2);
74 }
75 Buffer = new unsigned char[strlen(argv[1]) / 2];
76 BufferLen = strlen(argv[1]) / 2;
77
78 const char *Ptr = argv[1];
79 unsigned char *Target = Buffer;
80 while(*Ptr)
81 {
82 if(Ptr[0] < '0' || Ptr[0] > 'f') {printf("illegal character\n"); exit(3);}
83 if(Ptr[1] < '0' || Ptr[1] > 'f') {printf("illegal character\n"); exit(3);}
84 *Target = ((Ptr[0] - '0') << 4) | (Ptr[1] - '0');
85 Target++;
86 Ptr += 2;
87 }
88 }
89 
90 require_noerr (result = CreateAUGraph (graph, synthUnit), home);
91 // ok we're set up to go - initialize and start the graph
92 require_noerr (result = AUGraphInitialize (graph), home);
93 
94 CAShow (graph); // prints out the graph so we can see what it looks like...
95 
96 require_noerr (result = AUGraphStart (graph), home);
97 
98 MusicDeviceSysEx(synthUnit, Buffer, BufferLen);
99 
100 // ok we're done now
101 
102home:
103 if (graph) {
104 AUGraphStop (graph); // stop playback - AUGraphDispose will do that for us but just showing you what to do
105 DisposeAUGraph (graph);
106 }
107 return result;
108}

[My site [members.allegro.cc]] [Tetrominoes [members.allegro.cc]]

Go to: