% Demo: Play some FM instruments controlled by MIDI file

% Specify the base name of the MAT file produced by "midinote"
FileName = 'peanuts';

% Retrieve the notelist information
load(FileName)

% Specify maximum number of note events to play
% (long MIDI files can take a long time to convert
% to audio)
MaxNotes=200;

% Set up the instruments
fs=10e3;
instr1='horn';
%instr2='clarinet'; % You can specify different instruments
%instr3='bassoon';
%instr4='gong';

% Render notelists into audio.
% 
% The first argument to the "play"
% function specifies the instrument. In this demo the same instrument
% is used for each track, but you can specify different
% instruments, of course. The third entry in the "Notes" matrix
% address indicates the MIDI channel number to associate with
% a particular instrument. Channel 10 is percussion. Pay attention
% to the output of "midinote" to learn which MIDI channels are
% being used.
a1 = play(instr1,Notes(1:MaxNotes,:,1),fs);
a2 = play(instr1,Notes(1:MaxNotes,:,2),fs);
a3 = play(instr1,Notes(1:MaxNotes,:,3),fs);
a4 = play(instr1,Notes(1:MaxNotes,:,10),fs);

% Make sure all audio tracks are the same length
maxlength=max([length(a1) length(a2) length(a3) length(a4)]);
a1=[a1 zeros(1,maxlength-length(a1))];
a2=[a2 zeros(1,maxlength-length(a2))];
a3=[a3 zeros(1,maxlength-length(a3))];
a4=[a4 zeros(1,maxlength-length(a4))];

% Build stereo audio vector
audio = [a1+a2;a3+a4]';

% Scale audio waveform to fit in -1 to +1 range
audio = audio/max(abs(audio));

% Play the audio
sound(audio,fs)

% Save audio to a .WAV file
%wavwrite(audio,fs,16,FileName)



