Showing posts with label Sound Analysis. Show all posts
Showing posts with label Sound Analysis. Show all posts

Thursday, 16 April 2009

Analyzing a .wav file

In the previous article we found how to create a simple audio music file. Here, we are going to analyze it, i.e., to find out the fundamental frequency and other parameters. The code given below plots the .wav file and it power spectrum.

%Code Starts here

[y, Fs] = wavread(file); % y is sound data, Fs is sample frequency.
t = (1:length(y))/Fs; % time

ind = find(t>0.1 & t<0.12); % set time duration for waveform plot
figure; subplot(1,2,1)
plot(t(ind),y(ind))
axis tight
title(['Waveform of ' file])

N = 2^12; % number of points to analyze
c = fft(y(1:N))/N; % compute fft of sound data
p = 2*abs( c(2:N/2)); % compute power at each frequency
f = (1:N/2-1)*Fs/N; % frequency corresponding to p

subplot(1,2,2)
semilogy(f,p)
axis([0 4000 10^-4 1])
title(['Power Spectrum of ' file])

%Code ends here

querrymail@gmail.com

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