.st0{fill:#FFFFFF;}

Piano Application in MATLAB 

 June 22, 2021

By  Prithvi

Piano fundamentals

I am sure most of you would have heard some beautiful melodies or maybe can play some yourself, in this blog we will see how it's possible to create some tunes in MATLAB. In this blog, we will use the terms keyboard and piano interchangeably since we are going to make a virtual piano application.

Pianos come in many different key number layouts like 88,67,32 keys etc. We will be considering a 32 key piano as shown below and understand the layout and terms related to it.


Piano Blog key piano layout-1

The above piano configuration has 19 white keys and 13 black ones. Each of these keys plays a sound of different frequency when they are struck. An octave is an interval between two keys where one of the keys has double the frequency of the other. Conventionally ‘C’ is considered the first key of an octave. We can design a simple piano layout in MATLAB using push buttons which in our program looks like this:

Piano Blog MATLAB piano layout

Piano note frequencies

Since the different sounds played using a piano is dictated by their frequency we can make use of this formula to determine the same:
\left ( \sqrt[12]{2} \right )^{n-49} \times 440 HZ

As we mentioned each octave starts with ‘C’ and is followed by ‘D’,’ E’,’ F’,’ G’,’ A’, and ‘B’. The keys have a letter followed by a number to represent the octave. In our program, we start with the 3rd octave and F note so the white keys will be ‘F3’,’ G3’,’ A3’,’ B3’,’ C4’,’ D4’ and so on. If we take a look at the black keys we see that they have 2 names: 1 for a higher note and 1 for a lower note. These are called half frequencies and they are called flat or sharp. For example, the note between F and G can be called as F sharp or G flat, in general, it is called as a  sharp of the lower note and flat of a higher note.

In the formula seen above, the letter ‘n’ refers to the note number which is assigned to each note in a piano. The note number of some notes can be referred from Wikipedia as shown below.

Piano Blog Key frequency


Hence we can just plug in the note number to the above formula to get the required frequency of a note. This frequency is then passed to a function that forms the waveform for the sound wave and then played using the sound function in MATLAB.

MATLAB function to produce the piano sound waveforms

function wave = wavefunc(app,notenum,time)
t = 0:1/app.samplefreq:4/time;
%Formula to determine frequency of anote from its notenumber
freq = 440*2^((notenum-49)/12);
%Code to waves to simulate the sound of a piano
wave = sin(1* 2 * pi *freq * t) .* exp(-0.0004 * 2 * pi * freq * t) / 1;
wave = wave+sin(2* 2 * pi *freq * t) .* exp(-0.0004 * 2 * pi * freq * t) / 2;
wave = wave+sin(3* 2 * pi *freq * t) .* exp(-0.0004 * 2 * pi * freq * t) / 4;
wave = wave+sin(4* 2 * pi *freq * t) .* exp(-0.0004 * 2 * pi * freq * t) / 8;
wave = wave+sin(5* 2 * pi *freq * t) .* exp(-0.0004 * 2 * pi * freq * t) / 16;
wave = wave+sin(6* 2 * pi *freq * t) .* exp(-0.0004 * 2 * pi * freq * t) / 32;
wave= wave+(wave.*wave.*wave);
wave=wave/6;
end

MATLAB code for callback of the push buttons   

 function A5ButtonPushed(app, event)                
notenum=61;                
wave=app.wavefunc(notenum,app.time);                
sound(wave,app.samplefreq,24);                
 if (app.rec==1)                    
app.song=[app.song wave];                
 end        
end

Improving the design and functionality of the application

Since our application is very bland at the current stage we can add a background image to make it look better. Also, to improve the functionality we add 3 more buttons:

  • Record: This push button allows us to record our piano keypresses and finally store them in a .wav file format
  • Long press: This state button allows us to enable and disable long-press which allows us to simulate the sound of a long press that is possible on a real piano.
  • Happy Birthday theme: This push button has a pre-defined code that automatically plays the happy birthday theme song.

After changing the look and adding more buttons, the application looks like this       

Piano Blog App look

Happy birthday theme song

We can make use of the following image to write the pre-defined code to play the happy birthday song:

Piano Blog HBD musical notes

 SOURCE : GOOGLE

To write the code, we just have to follow the notes given above and pass the frequency to the ‘wavefunc’ and sound function accordingly to get the song. In our program, we start from the third octave. So the notes for the first line will be A3A3 B3A3 D4C4#.

Code for first line of the song

notenum=37; % A3
wave=app.wavefunc(notenum,app.time);
sound(wave,app.samplefreq,24);
pause(.65)
notenum=37; % A3
wave=app.wavefunc(notenum,app.time);
sound(wave,app.samplefreq,24);
pause(.65)
notenum=39; % B3
wave=app.wavefunc(notenum,app.time);
sound(wave,app.samplefreq,24);
pause(.65)
notenum=37; % A3
wave=app.wavefunc(notenum,app.time);
sound(wave,app.samplefreq,24);
pause(.65)
notenum=42; % D4
wave=app.wavefunc(notenum,app.time);
sound(wave,app.samplefreq,24);
pause(.65)
notenum=41; % C4#
wave=app.wavefunc(notenum,app.time/2);
sound(wave,app.samplefreq,24);
pause(1.4)

Sample audio of the song

Conclusion

We made use of the frequency properties of a piano and the sound function in MATLAB to make a piano application. This allows us to play tunes of our choice. Hence MATLAB can be used to make many interesting and fun applications like this.

Get instant access to the code, model, or application of the video or article you found helpful! Simply purchase the specific title, if available, and receive the download link right away! #MATLABHelper #CodeMadeEasy

Ready to take your MATLAB skills to the next level? Look no further! At MATLAB Helper, we've got you covered. From free community support to expert help and training, we've got all the resources you need to become a pro in no time. If you have any questions or queries, don't hesitate to reach out to us. Simply post a comment below or send us an email at [email protected].

And don't forget to connect with us on LinkedIn, Facebook, and Subscribe to our YouTube Channel! We're always sharing helpful tips and updates, so you can stay up-to-date on everything related to MATLAB. Plus, if you spot any bugs or errors on our website, just let us know and we'll make sure to fix it ASAP.

Ready to get started? Book your expert help with Research Assistance plan today and get personalized assistance tailored to your needs. Or, if you're looking for more comprehensive training, join one of our training modules and get hands-on experience with the latest techniques and technologies. The choice is yours – start learning and growing with MATLAB Helper today!

Education is our future. MATLAB is our feature. Happy MATLABing!

About the author 

Prithvi

Engineering student with a keen interest to learn and implement new things. Currently working as a MATLAB developer at MATLAB helper.

  • Sowbhagya Appalla says:

    The idea is interesting and attractive. The explanation is picture-clear. I feel this as one of the best blogs I have studied till date.

  • {"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}

    MATLAB Helper ®

    Follow: YouTube Channel, LinkedIn Company, Facebook Page, Instagram Page

    Join Community of MATLAB Enthusiasts: Facebook Group, Telegram, LinkedIn Group

    Use Website Chat or WhatsApp at +91-8104622179

    >