MATLAB Code
mlab_music.m
% HAIL PURUDE in MATLAB % Written by: Jeffrey Kubascik clear; % Sampling period delta = 1/10000; % Duration of the notes (beats) Wn = 4; Hn = 2; Qn = 1; dQn = 1.5 * Qn; En = 1/2; Sn = 1/4; % Frequency of the notes (Hz) C4 = 264; % Base to calculate all other frequencies B5 = C4 * 15/8 * 2; A5 = C4 * 5/3 * 2; G5 = C4 * 3/2 * 2; F5 = C4 * 4/3 * 2; E5 = C4 * 5/4 * 2; D5 = C4 * 9/8 * 2; C5 = C4 * 2; B4 = C4 * 15/8; A4 = C4 * 5/3; G4 = C4 * 3/2; F4 = C4 * 4/3; E4 = C4 * 5/4; D4 = C4 * 9/8; C4 = C4; R = 0; % A rest (frequency=0 => sin(0)=0 => no sound, since it is constant) % Song data hail_purdue = [Hn,E4, Qn,F4, Qn,G4, dQn,A4, En,B4, Qn,C5, Qn,C5, ... Qn,D5, En,D5, En,D5, Qn,A4, En,B4, En,B4, Hn,C5, Qn,C5, Qn,R, ... Hn,C5, Qn,C5, Qn,B4, dQn,A4, En,B4, Qn,C5, Qn,C5, Qn,B4, En,F4, En,G4, ... Qn,A4, En,G4, En,E4, Hn,B4, Qn,B4, Qn,R, dQn,E4, En,E4, ... Qn,F4, Qn,G4, dQn,A4, En,B4, Qn,C5, En,C5, En,C5, Qn,D5, Qn,D5, Qn,A4, Qn,B4, ... Hn,C5, Qn,C5, Qn,R, dQn,F4, En,G4, Qn,A4, Qn,F4, Qn,E4, Qn,A4, ... Qn,C5, Qn,E4, dQn,F4, En,C5, dQn,B4, En,A4, Hn,A4, Qn,A4, Qn,R]; % Generate the music waveform y = generate_waveform(hail_purdue, 160, delta, 1); % Create a wav file from the music waveform wavwrite(y, 1/delta, 'hail_purdue.wav'); % Place the tune 2x faster (2x tempo) y = generate_waveform(hail_purdue, 2*160, delta, 1); % Create a wav file from the music waveform wavwrite(y, 1/delta, 'hail_purdue_2xfast.wav'); % Scale the frequency by 2 y = generate_waveform(hail_purdue, 1*160, delta, 2); % Create a wav file from the music waveform wavwrite(y, 1/delta, 'hail_purdue_2xfreq.wav');
generate_waveform.m
function waveform = generate_waveform(song, tempo, delta, freq_scale) % Generate the music waveform y = []; length = size(song) / 2; % Number of notes in the array for index = 1:length(2); duration = 60 / tempo * song(index*2 - 1); % Duration of the note frequency = song(index*2); % Frequency of the note % Create a time vector t = 0:delta:duration; % Create the sound wave form % Here, I have modified the sin wave to decay linearly. This helps % distinguish each note, and also prevents any "jumps" in the waveform % i.e. the end of note ends with a non-zero value, and the next note % starts at zero. This creats a "tick" noise. x = sin(2*pi*frequency*t*freq_scale) .* (1 - t/duration); % Append the note to our music waveform y = [y x]; end waveform = y;