I got bored and curious tonight, so I worked on it for about half an hour. Here is the code I came up with, which gives more synthesizer-sounding music than piano, but not too bad. It plays the first few measures of "Twinkle, Twinkle, Little Star," approximately anyway. I don't know how to play the piano, but I recall the basic tune from my days as a violinist many moons ago. The keyfreqs.txt is simply a sorted list of piano key frequencies borrowed from
here. I don't know anything about music theory, so I can't explain why the notes don't sound quite like a piano. Perhaps I need to include a higher number of overtones, but that just takes longer computationally and I'm not bored enough to wait around for that.
😛
Anyway, here's the sloppy code.
overtones=25;%number of overtones to include
duration=0.5;%seconds
SampleFreq=44100;%44.1 kHz sample rate
duration=[1,1,1,1,1,1,2,1,1,1,1,1,1,2].*duration;
keys=[49,49,56,56,58,58,56,55,55,53,53,51,51,49];
NumNotes=length(keys);
freqs=dlmread('keyfreqs.txt');
Instrument=0;
Song=[];
%Generate the sound waveform
for i=1:NumNotes
%Allow for variable note duration
NumPoints=duration(i)*SampleFreq;
t=linspace(0,duration(i),NumPoints);
% f=fbase*2^((i-a)/12);%Produce octaves for piano
key=keys(i);
y=MakeSound(t,freqs(key),overtones,Instrument);
Song=vertcat(Song,y');
end
soundsc(Song,SampleFreq);
function y=MakeSound(t,f,overtones,Instrument)
y=sin(2.*pi.*f.*t);
if overtones~=0
for i=1
😱vertones
if Instrument==0
%Perfect harmonic overtones
y=y+sin(2.*pi.*f.*i.*t);
elseif Instrument==1
%odd multiples only
y=y+sin(2.*pi.*f.*(2.*i-1).*t);
elseif Instrument==2
%even multiples only
y=y+sin(2.*pi.*f.*2.*i.*t);
end
end
end