MATLAB Answers

create a piece of music using matlab??

Asked by Passband Modulation on 21 Sep 2012
Latest activity Answered by Cliff Bradshaw
on 22 Jul 2015

given a note file named “toneA.m"

------ note A-----

 clear all
 F_A=440; %Frequency of note A is 440 Hz

The frequencies of notes B, C#, D, E and F# are 493.88 Hz, 554.37 Hz, 587.33 Hz, 659.26 Hz and 739.99 Hz, respectively.

how to write a MATLAB file to produce a piece of music with notes in the following order : A, A, E, E, F#, F#, E, E, D, D, C#, C#, B, B, A, A. Assign the duration of each note as 0.3s.


my question is how do make a series of notes in just a note file, so that they sound like a piece of music?

Sean de Wolski
on 21 Sep 2012

In grad school I figured out how to play every Linkin Park song:

Cliff Bradshaw
on 22 Jul 2015

There is a useful example set called JukeBox() which can be downloaded here:

You can use it to play songs from Zelda and Tetris and Star Wars


No products are associated with this question.

4 Answers

Answer by Star Strider
on 21 Sep 2012

I suggest:

notecreate = @(frq,dur) sin(2*pi* [1:dur]/8192 * (440*2.^((frq-1)/12)));
notename = {'A' 'A#' 'B' 'C' 'C#' 'D' 'D#' 'E' 'F' 'F#' 'G' 'G#'};
song = {'A' 'A' 'E' 'E' 'F#' 'F#' 'E' 'E' 'D' 'D' 'C#' 'C#' 'B' 'B' 'A' 'A'};
for k1 = 1:length(song)
    idx = strcmp(song(k1), notename);
    songidx(k1) = find(idx);
dur = 0.3*8192;
songnote = [];
for k1 = 1:length(songidx)
    songnote = [songnote; [notecreate(songidx(k1),dur)  zeros(1,75)]'];
soundsc(songnote, 8192)


Answer by Daniel
on 21 Sep 2012

There are a number of things on the FEX. For example FEX:Matlab Piano.

Answer by Wayne King
on 21 Sep 2012
Edited by Wayne King
on 21 Sep 2012

Simple sine waves are not going to sound like music even if you string them together. I'm not a music expert by any stretch of the imagination, but an A played on a piano vs. guitar sounds different (and much richer) because of the harmonic structure.

I have not done the notes in the order you give, but you can easily modify:

 F_A = 440; %Frequency of note A is 440 Hz
 F_B = 493.88;
 F_Csharp = 554.37; 
 F_D = 587.33;
 F_E = 659.26;
 F_Fsharp = 739.9;
 notes = [F_A ; F_B; F_Csharp; F_D; F_E; F_Fsharp];
 x = cos(2*pi*notes*t); 
 sig = reshape(x',6*length(t),1);


on 10 Oct 2014

I'm able to replicate your example.

But, what if instead of x being cos (2*pi*note*t), x is defined as: 0.25* (2*pi*F_A*t) + 0.5* (2*pi*F_B*t) + 0.75* (2*pi*F_C*t)?

I'm not sure how to setup the constants outside of the cosine functions.

Answer by Cliff Bradshaw
on 22 Jul 2015

There is a free set of four files called "MATLAB JukeBox" that can be downloaded from GitHub:

If you look at the individual song files you'll be able to figure out the syntax.

By typing "JukeBox()" into the console you can play three songs that come in the package!

Hope this helps!


Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply today