% Script to create tunes in the form of pure tones
% It really is only designed for simple tunes spanning less than 1 octave in 4/4 time

clear all;
% make the pitches for the 12 notes from a start pitch using equal temperament tuning
f0 = 440;
n_split = 12;
num_pitches = 25; % number of different pitches (2 octaves in this case)

for p = 1:num_pitches
    pitch(p) = f0 * 2^((p-1)/n_split);
end

display('pitch sequence is in form of vector where 12 notes of octave are numbered 1 to 13 (rest =0)  ')
pitch_seq = input('enter pitch sequence for tune as row vector in square brackets, e.g. [1 3 5 1 1 3 5 1 5 6 8 5 6 8 ] or [1 3 5 6 0 8 10 12 13]: ');
display('note/rest duration sequence is in form of vector where quaver = 1/2, crotchet = 1, minim = 2, semibreve = 4 : ')
dur_seq = input('enter note/rest durations as vector in square brackets of same length as pitch vector (e.g. [.5 .5 .5 .5 .5 .5 .5 .5 .5 .5 1 .5 .5 1] or [1 1 1 1 1 1 1 1 1]): ');
note = input('enter absolute duration (ms) corresponding to crotchet (e.g. 500) ');
srate = 44100;  % sample rate
wdms = 20;      % gating window in ms


sig1 = [];  % prepare sound vector
for q = 1:length(pitch_seq)     % for number of pitches

    t = [0: 1/srate : dur_seq(q)*note/1000];    % define time vector

    if pitch_seq(q) == 0    % if rest
        wav = zeros(1,length(t));
    else
        wav = sin ( 2*pi * pitch(pitch_seq(q)) * t );   % frequency pitch(pitch_seq(q)) vector
        wav = 0.2 * wav/std(wav);       % fix rms level noise
        wav = wind(srate,wdms,wav);     % window
    end
    sig1 = [sig1 wav];  % add
end

sig1 = [sig1', sig1'];  % make stereo signal
wavwrite(sig1, srate, 'sequence');
sound(sig1,srate)