%% Compile and Play MIDI Messages
% Get the name of an available output MIDI device on your system.

mInfo = mididevinfo;
midiDeviceName = mInfo.output(1).Name;

% Create a mididevice object.

device = mididevice(midiDeviceName);

%  Create a MIDI message array.

msgs = [];
for ii = 1:8
    msgs = [msgs;midimsg('Note',1,20+8*ii,64,1,ii)];
end

% To listen to the MIDI messages, send the MIDI messages to your device.

midisend(device,msgs)

%
% To compile the previous steps, encapsulate the code in a function and then call mcc.
% function playMusic1()
%     mInfo = mididevinfo;
%     midiDeviceName = mInfo.output(1).Name;
%     device = mididevice(midiDeviceName);
%
%     msgs = [];
%     for ii = 1:8
%         msgs = [msgs;midimsg('Note',1,20+8*ii,64,1,ii)];
%     end
%
%     midisend(device,msgs)
% end

mcc playMusic1 -m -w disable

% Execute the compiled code. You will not hear any sound. This is because the executable opened, sent the MIDI messages to the queue, and then closed, aborting its commands before the MIDI messages had a chance to play.

!playMusic1.exe

% To keep the executable open long enough for the MIDI messages to play, add a pause to the executable. Set the duration of the pause to equal the duration of the MIDI messages.
% function playMusic2()
%     mInfo = mididevinfo;
%     midiDeviceName = mInfo.output(1).Name;
%     device = mididevice(midiDeviceName);
%
%     msgs = [];
%     for ii = 1:8
%         msgs = [msgs;midimsg('Note',1,20+8*ii,64,1,ii)];
%     end
%
%     midisend(device,msgs)
%     pause(msgs(end).Timestamp)
% end

mcc playMusic2 -m -w disable

% Play the compiled executable. The sound that plays through your MIDI device is the same as the uncompiled version.

!playMusic2.exe

% Copyright 2019 The MathWorks, Inc.