I have been attempted to do this for a long time, but only now I have some time to actually try it out. As it turned out, to have Matlab playing music is relatively easy, to have Matlab playing appealing music is way harder than I have imagined.
The core part is this Matlab function:
This function takes a vector and simply output it to the audio device in sequence. Values in the vector is the relative amplitude. Values larger than 1 will be ignored.
The default sample rate is 8000, so you'll need 8000 data point to get 1 second of sound. If we want higher sample rate, then have to play the vector at a higher sample rate:
Now, it's very easy to generate such a vector:
First, generate a vector that represents time points:
The first line generates a vector of 0.5*16000 values. That is 0.5 seconds in 16000 sample rate. The second line generates a sine wave of 440Hz for 0.5 seconds.
440Hz is A4. 12 half tones double the frequency. From C4 to A4 is 9 half tones. So C4 is 440*2^(-9/12)Hz. So for a simple C4 to C5, here's the frequencies:
So we can simply do this:
n1=sin(440*2^(-9/12)*2*pi*tp); % C n2=sin(440*2^(-9/12)*2*pi*tp); % C n3=sin(440*2^(-2/12)*2*pi*tp); % B n4=sin(440*2^(-2/12)*2*pi*tp); % B n5=sin(440*2^(0/12)*2*pi*tp); % A n6=sin(440*2^(0/12)*2*pi*tp); % A n7=sin(440*2^(-2/12)*2*pi*tp); % B sound(n1,16000); sound(n2,16000); sound(n3,16000); sound(n4,16000); sound(n5,16000); sound(n6,16000); sound(n7,16000);
This gives us "twinkle twinkle little star". Here I output the audio into .wav file:
On hearing it, you notice that, it sounds very uncomfortable, and there's no variation of amplitude within one note.
The problem is, I'm using "pure tone" here. Real instruments generate sound with a very rich composition of different frequency, phase and amplitude, that we haven't take into consideration here. Next post I'll try to mimic the sound generated by a hitting a key on a piano.