Thursday, 16 April 2009

Generate Music using MATLAB

This is an interesting, but simple experiment which has many utility. The following code can genrate a .wav file to play a sound of required frequency.

Before proceeding you should set the following:
filename---> give a name to your fantastic music file (say 'mymusic.wav')
f-----------> fundamental frequency (say f=256) in Hz.
d----------> time duration (say t =5) in seconds.
p----------> it is vector of amplitudes of length n. (say it values be [1 0.8 0.1 0.04]

%Code starts here

Fs=22050; nbits=8; % frequency and bit rate of wav file
t = linspace(1/Fs, d, d*Fs); % time
y = zeros(1,Fs*d); % initialize sound data
for n=1:length(p);
y = y + p(n)*cos(2*pi*n*f*t); % sythesize waveform
end
y = .5*y/max(y); % normalize. Coefficent controls volume.
wavwrite( y, Fs, nbits, filename)

%Code ends here

querrymail@gmail.com

0 comments: