Thursday, 24 March 2011

Making a MATLAB Media Player

Recently i got a request to write a blog on making a media player on MATLAB. This example shows you a simple way to make a mp3 player in steps. In this step, i will write how to setup the initial background and design base GUI using GUIDE.


Using a mp3 reader
MATLAB does not have an inbuilt mp3 reader function. mp3 is a  encoded which you need to convert to wavfile before reading it. But Dont worry, matlab central provides you all.

go to this download link and download the zip file.
http://www.mathworks.com/matlabcentral/fileexchange/6152-mp3write-and-mp3read

extract the folder and save it to your current directory with name mp3readwrite.

Now you need to add the path of these files in your matlab file.
path(path,'mp3readwrite');
To verify that you have done right, put a mp3 file with name playfile.mp3 in your current directory and run this command
[y f]=mp3read('playfile.mp3');
if you get undefined function or variable mp3readwrite, then check the path of the file inside folder and change the path accordingly.

Generating gui fig using GUIDE
first step is to generate a fig file which contains the basic component of a media player. (As in fig 1)

Fig 1 : sample media player GUI
  1. A playlist (ListBox)
  2. An Add File button (PushButton)
  3. A Volume Silder (Slider)
  4. A play Progress Slider(Slider)
  5. Play/Pause Button (Push Button)
  6. Stop Button (Push Button)
  7. Visualization (Axis)
See fig 2 to see the sample tag name used in this example
save this file as mmp.fig and this will generate a mmp.m file

Fig 2 : GUIDE TAGS

 
 In the previous section, We have seen the basic GUI fig. In this section, we would be learning to add basic features in this player.

Making the playlist work
Making the playlist is easy task. Since we need the full path for playing purpose and we need to show only title information in playlist. So we will maintain a spearate list playfiles for full path.

Add this to your opening function 

function mmp_OpeningFcn(hObject, eventdata, handles, varargin)
handles.playfiles=[];
% Update handles structure
guidata(hObject, handles);
We have made the add button. Modify the callback for pladd 
function pladd_Callback(hObject, eventdata, handles)
% hObject    handle to pladd (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
[f g]=uigetfile;
p=get(handles.playlist,'String');
p{length(p)+1}=[f];
set(handles.playlist,'String',p);
handles.playfiles{length(handles.playfiles)+1}=[g '\' f];
guidata(hObject,handles);

As you can see, uigetfile is used to open a filebrowser and then i store the filename and its path into a list playfiles.
I also update the playlist string property with the file name which is shown on playlist on player.

How to play Audio
There are some option like wavplay or sound in matlab which can play your audio. But you cannot pause or resume it once you have started it. We will use audioplayer class of MATLAB for our purpose.

This small code tells you how to play a wav file by audioplayer object.
first read the .wav file using wavread
[y f]=wavread('aa.wav');
now make an instance of audioplayer with this y and f.
pl=audioplayer(y,f);
pl is the handle to this audioplayer.
Now you can use the play/pause/resume/stop methods to do the respective operations. As an Example:
play(pl);
pause(pl);
resume(pl);
You can get the total sample and current sample number using get method over pl object as 
cs=get(pl,'CurrentSample');
ps=get(pk,'TotalSamples');
To get the progress of the sound file, you can use
ctime=cs/ps;
you can use isplaying option to check whether the pl is running or not.
f=isplaying(pl);
You can combine this with mp3reader to read a mp3 file
cfile='aa.mp3';
extn=cfile[end-2:end];
switch (extn)
  case 'mp3'
        [y f]=mp3read(cfile);
  case  'wav'
       [y f]=wavread(cfile);
end
pl=audioplayer(y,f);
play(pl);
There is one more cool thing to do here. You can make a function which gives you the current progress of music and it will be called automatically by matlab after a certain time if you give its name to audioplayer object. let us see how we can do it.
first make an new m file and save it as UpdateWin.m and write the following in this

function UpdateWin(pl)
%global pl;
c=get(pl,'CurrentSample');
t=get(pl,'TotalSamples');
disp(c/t);

Now make a function f where you can pass this pl.
f=@() UpdateWin(pl);
Now set this f as timer function of pl.
set(pl,'TimerFcn','f()');
Timercall time is automatically set as TimerPeriod: 0.0500 in seconds


Whole piece of code will look like as
cfile='aa.mp3';
extn=cfile[end-2:end];
switch (extn)

  case 'mp3'
        [y f]=mp3read(cfile);

  case  'wav'
       [y f]=wavread(cfile);
end
pl=audioplayer(y,f);

f=@() UpdateWin(pl);
set(pl,'TimerFcn','f()');
play(pl);
Adding Playing Callback
In playbuttonCallback function add the following code for starting the playing of music. Steps we are following are
1. Selecting the file name from playlist
v=get(handles.playlist,'Value');
cfile=handles.playfiles{v};
2. create the player and assign it to the player in handles structure.
extn=cfile[end-2:end];
switch (extn)
  case 'mp3'
        [y f]=mp3read(cfile);
  case  'wav'
       [y f]=wavread(cfile);
end
pl=audioplayer(y,f);
f=@() UpdateWin(pl);
set(pl,'TimerFcn','f()');
handles.pl=pl;
3. Now play this if the player is not running else pause it
if isrunning(pl)
    pause(pl);
else
  resume(pl);
end
Adding other callbacks
making other call backs are pretty easy.
just write following in stop callback
stop(pl);
Making the playersilder move
 Noe it is time to move your player slider to show the progress.
Update your UpdateWin file as following
function UpdateWin(pl)
c=get(pl,'CurrentSample');t=get(pl,'TotalSamples');
%disp(c/t);
h=guidata(pl);
set(h.playslider,'value',c/t);
Enjoy Your player is working now

Wednesday, 23 March 2011

Starting with neural network in matlab

The neural networks is a way to model any input to output relations based on some input output data when nothing is known about the model. This example shows you a very simple example and its modelling through neural network using MATLAB.

Actual Model
Let us take that our model has three inputs a,b and c and generates an output y. For data generation purposes, let us take this model as
y=5a+bc+7c;

we are taking this model for data generation. In actual cases, you dont have the mathematical model and you generate the data by running the real system.

Let us first write a small script to generate the data
    a= rand(1,1000);
    b=rand(1,1000);
    c=rand(1,1000);
    n=rand(1,1000)*0.05;

    y=a*5+b.*c+7*c+n;
n is the noise, we added deliberately to make it more like a real data. The magnitude of the noise is 0.1 and is uniform noise.

So our input is set of a,b and c and output is y.
    I=[a; b; c];
    O=y;
Understanding Neural Networks
Neural network is like brain full of nerons and made of different layers.
The first layer which takes input and put into internal layers or hidden layers are known as input layer.
The outer layer which takes the output from inner layers and gives it to outer world is known as output layer.

The internal layers can be any number of layers.

Each layer is a basically a function which takes some variables (in the form of vector u) and transforms it to another variable(another vector v) by multiplying it with coefficients and adding some biases b. These coefficient is known as weight matrix w. Size of the v vector is known as v-size of the layer.
v=sum(w.*u)+b

So we will make a very simple neural network for our case- 1 input and 1 output layer. We will take the input layer v-size as 5. Since we have three input , our input layer will take u with three values and transform it to a vector of size 5. and our output layer now take this 5 element vector as input and transforms it to a vector of size 1 because we have only on output.

Creating a simple Neural FF Network
We will use matlab inbuilt function newff for generation of model.
First we will make a matrix R which is of 3 *2 size. First column will show the minimum of all three inputs and second will show the maximum of three inputs. In our case all three inputs are from 0 to 1 range, So
R=[0 1; 0 1 ; 0 1];
Now We make a Size matrix which has the v-size of all the layers.
S=[5 1];
Now call the newff function as following
  net = newff([0 1;0 1 ;0 1],S,{'tansig','purelin'});
net is the neural model. {'tansig','purelin'} shows the mapping function of the two layers. Let us not waste time on this.

Now as each brain need training, this neural network too need it. We will train this neural network with the data we generated earlier.
net=train(net,I,O);
Now net is trained. You can see the performance curve, as it gets trained.

So now simulate our neural network again on the same data and compare the out.puts.
O1=sim(net,I);
plot(1:1000,O,1:1000,O1);

 You can observe how closely the the two data green and blue follow each other.
Let us try scatter plot between simulated output and actual target output.
scatter(O,O1);

Let us observe the weight matrix of the trained model.

net.IW{1}
 -0.3684    0.0308   -0.5402
    0.4640    0.2340    0.5875
    1.9569   -1.6887    1.5403
    1.1138    1.0841    0.2439
net.LW{2,1}
-11.1990    9.4589   -1.0006   -0.9138
Now test it again on some other data. What about a=1,b=1 and c=1;

So input matrix will be [1 1 1]';
y1=sim(net,[1 1 1]');
you will see 13.0279. which is close to 13 the actual output (5*1+1*1+12*1);


Updates:
1. O and T are same variable. define O=T or just replace T everywhere with O
2. S=[5 1], so while defining newff you should pass S or [5 1]. [4 1] is incorrect

Thursday, 17 March 2011

Understanding Scope: The Life Span of a Variable

Scopes:
All the variable in any language have a span of life which is called their scope. Fortunately all variables created in MATLAB by a script or command line are alive until you delete them by calling clear or you shutdown matlab. While all the variable in the function become alive when that function is called and they are cleared automatically as soon as function call is ver.
if you call the function again, these variables are created again and they have lost their previous value.
try this:
make a function my_fun and save this as my_fun.m
function f=my_fun(x)
y=2*x;
f=log(y);
Now call this function from command line or script file
g=3;
h=my_fun(g);
Now type
whos
to see the variables created and you would see only g and h , no y.x or f variables are there.

Suppose you want that a variable created inside a function should not get deleted

How to make these variables' scope large:
there are two ways. One of the way is by declaring the variable global. Let us apply this above. In function definition, modify it as

function f=my_fun(x)
global y;
y=2*x;
f=log(y);
Now on command line, write
g=3;
h=my_fun(g);
global y;
Now type
whos
to see the variables. You can now see the variable y with value 6.
Remember you need to declare the variable global every place you want to use it. If you dont do this, then it is just a local variable unlinked from the global one even when their name are same