create a piece of music using matlab??

289 views (last 30 days)
Passband  Modulation
Passband Modulation on 21 Sep 2012
Commented: Walter Roberson on 31 May 2022
given a note file named “toneA.m"
------ note A-----
clear all
Fs=8000;
Ts=1/Fs;
t=[0:Ts:1];
F_A=440; %Frequency of note A is 440 Hz
A=sin(2*pi*F_A*t);
sound(A,Fs);
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.
  4 Comments
Saravanakumar Chandrasekaran
How to store this sound as audio file say for example a .WAV or .MP3 in matlab

Sign in to comment.

Answers (7)

Star Strider
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);
end
dur = 0.3*8192;
songnote = [];
for k1 = 1:length(songidx)
songnote = [songnote; [notecreate(songidx(k1),dur) zeros(1,75)]'];
end
soundsc(songnote, 8192)
  21 Comments
Walter Roberson
Walter Roberson on 24 Jul 2020
tt=4/n:-1/fs:0; is not exactly the same as fliplr(t). For example let n=5 and fs=6. In forward direction the result would be approximations of 0, 1/6, 2/6, 3/6, 4/6 and then would stop because 5/6 would exceed 4/5. In the reverse direction you would get 4/5, 4/5-1/6=19/30, 4/5-2/6=7/15, 4/5-3/6=3/10, 4/5-4/6=2/15 and then stop because subtraction of another 1/fs would go below 0.
Walter Roberson
Walter Roberson on 24 Jul 2020
You do not have multiple channels, so there is no need to extract channels for the envelope. Multiple channels would require that you have multiple notes at the same time. I showed a framework for representing that, above, with each cell array entry indicating notes to be played at the same time.
Though it is not actually notes playing at the same time that is important. What is important for multiple channels is that you have representation of sound being emitted at different physical points, or sounds for different devices that might potentially get mixed down to a single physical point but with different treatment, but different flows of notes to be merged together for a single physical point is also a possibility. It depends on what you are trying to do. At the moment you are synthesizing one note at a time with one emission location, and one logical flow of notes, so you only have one channel. Multiple channels implies that there are multiple sources that you want to treat differently but you have a single mono source.

Sign in to comment.


Ryan Black
Ryan Black on 27 Dec 2017
Edited: Ryan Black on 16 Apr 2020
Yep, I built a comprehensive music synthesizer in MATLAB. Hear a song HERE:
Additive Synthesis manipulates and superimposes fundamental sine waves to create sounds with unique timbres. This models differential equation solution methods derived by Fourier (steady state) and Laplace (transient). The methods can be used to analyze periodic motion from springs, electrical circuits, heat transfer, sound! If you look the stuff up on Wikipedia, you will be disheartened by its complexity, yet it can be explained intuitively:
Most people live their whole mathematical lives thinking in terms of time (distance/speed of car vs time, force vs time, profit vs time). But not all systems are best understood/easy to solve this way. Like, it’s possible to graph the position of a spring vs time, but when conditions become more complex its insanely hard to!!! So we transform from the TIME domain to the…………. FREQUENCY domain!!! One such method is called a Fast Fourier Transform (FFT).
This allows us to analyze seemingly chaotic time-domain signals (cello tones, vowel sounds, etc.) by making sense of them in the frequency domain. The signal becomes a superposition of simpler frequency components with different scaling factors (rather than random wave scribbles). The more pleasing the signal, the more ordered (harmonic) the frequency components are on the graph. Such that {whistle, flute, ahhhhhh vowel} will look more clean on a frequency domain power spectrum graph and {ssssss consonant, engine grumbling} will be less clean though in the time domain this might be hard to distinguish.
At this point we can collect data or clean up the signal and inverse FFT back to the time domain for realistic sounds. This whole process is called sampling but you don't HAVE to be so technical. If you want to just add some harmonic (non-harmonic, too) sin waves together willy nilly and play them, they could still sound good, it will just be harder to achieve a desired effect without the empirical data. Although, I created a realistic bell using a more developed version of this guess-and-check method (using rand functions and transient power spectrums, mostly).
Other than the main theory (and applied music theory), the rest of building a synthesizer is being able to store and call arrays of data in fast user-friendly ways, figuring out quantitative equations for beats per minute, how to insert a variable diminished sustain into a volume envelope array, how to keep everything organized as to continue building the program.. So just tedious coding stuff is the bulk of the work.
Additive Synthesis Discrete Equation below (arrays/scalars are undefined in the code because I don't want to give you my entire program. Do some work on your own! To fully help you start I explained the arrays/scalars in the comments)
%%-------------------BUILD MASTER WAVE EQUATION-------------------------%%
%%----------------------------------------------------------------------%%
%%fLS for Loop Section, loop through "chord, harmonics, clusters"-------%%
for mm=1:length(chord)
if chord(mm)>0
[AM,FM]=modperiodic(modpackl,modpackh,chord(mm)*freq(qq),...
t,volumemast,volchildren,transfreq);
for nn=1:size(ppp,1)
if aspec(nn)>0
place=1-(((clustersize-1)/2)*offset);
flip1=0;
for oo=1:clustersize
dil=dilsize^(((clustersize-1)/2)+oo-1-flip1);
[randstab]=rndgen(error_overtonal);
if nn==1 || nn==2
[randstab]=rndgen(error_tonal);
end
%build wave
y = y + dil*AM.*ppp(nn,:).*...
sin(FM.*transfreq.*t*randstab*place*...
2*pi*nn*freq(qq)*chord(mm));
place=place+offset;
if oo>=clustersize/2
flip1=flip1+2;
end
end
end
end
end
end
end
%%NaL Noise added and loudness envelope applied-------------------------%%
y=((randi(100,1,length(volumemast))/200)-.25)...
.*noisethres.*volumemast.^2.5+y; %noise
y=y.*volumemast.^2.5; %volume envelope final contour
y=y/max(abs(y(1,:))); %and normalize!
% y = single row accumulative sound wave vector, time/amplitude normalized to volumemast
% ppp = transient amplitude spectrum proportion array (colsize is equal length as y, rowsize is equal to # overtones), time/amplitude normalized to volumemast
% mm, nn, oo = array element iterators
% freq(qq) = fundamental frequency, scalar (dependent on melody/modulation/8va/vb/chord iteration data)
% transfreq = transient non-sinusoidal frequency modulation envelope, time normalized to volumemast (must be smooth)
% chord(mm) = fundamental frequency multiplier, scalar
% t = note time vector (equal length as y) sampling at Fs
% FM = high/low transient Frequency Modulation vector (equal length as y), dependent on freq(qq) and time/amplitude normalized to volumemast
% AM = high/low transient Amplitude Modulation Array (equal length as y), dependent of freq(qq) and time/amplitude normalized to volumemast
% randstab = random number between 1+delta and 1-delta regenerated each loop in function: randgen... Acts as a pitch destabilizer for tones and overtones.
% error_tonal/error_overtonal = pitch destabilizer scalars for randgen function
% place = tone cluster scalar, superimposes equally-spaced-f notes around a max-power tonal center
% offset = linear additive iterator for place, scalar
% clustersize = number of superimposed clustered notes for place, scalar
% dil/dilsize/flip1 = cluster power dilation variables
% volumemast = MASTER transient ADSR vector (equal length as y)
% noisethres = transient noise vector, time/amplitude normalized to volumemast
  8 Comments
Chiemela Victor Amaechi
Chiemela Victor Amaechi on 24 Nov 2019
Edited: Chiemela Victor Amaechi on 24 Nov 2019
@Ryan, that's cool. I will like to see the Mr Polygon GUI created for this.
@Passband, you might want to see some files created on File Exchange on Music Piano and other links. Do look at these links and other references:
For References:
Ryan Black
Ryan Black on 16 Apr 2020
Oh my I have come so far since this post :/ I don't even know what to say. Uh...
Look here?

Sign in to comment.


Daniel Shub
Daniel Shub on 21 Sep 2012
There are a number of things on the FEX. For example FEX:Matlab Piano.

Wayne King
Wayne King on 21 Sep 2012
Edited: 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:
Fs=8000;
Ts=1/Fs;
t=[0:Ts:0.3];
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);
soundsc(sig,1/Ts)
  12 Comments
tom cohen
tom cohen on 21 Oct 2021
thank you. maybe you could help with this too please?
why can't i play this?
fs = 8192;
dt = 1/fs;
L = 1;
L=L*fs;
t = (0:1:L-1)*dt-0.5;
NoteFreq1 = 261.63;
NoteFreq2 = 659.26;
NoteFreq3 = 440;
NoteDuration = 0.25;
NoteSpace =0.1;
Note=abs(t)<=((NoteDuration/2).*cos(2*pi*NoteFreq1*t)+((NoteDuration/2)+ NoteSpace).*cos(2*pi*NoteFreq2*t)+((NoteDuration/2)- NoteSpace).*cos(2*pi*NoteFreq3*t));
CleanInput = audioplayer(Note, fs);
play(CleanInput);
Walter Roberson
Walter Roberson on 21 Oct 2021
Note=abs(t)<=((NoteDuration/2).*cos(2*pi*NoteFreq1*t)+((NoteDuration/2)+ NoteSpace).*cos(2*pi*NoteFreq2*t)+((NoteDuration/2)- NoteSpace).*cos(2*pi*NoteFreq3*t));
% ^^^
You have a comparison, so the output is logical. You cannot play a logical vector.
You could double(Note) to get a series of 0 and 1 values and play that, but it isn't clear that is what you would want.

Sign in to comment.


Cliff Bradshaw
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!

Aurelija V
Aurelija V on 10 Mar 2016
Hi, I have a question about the music playing in MatLab... How to make the melody sound like violin? I get a melody, but it's like a sintenizer, and i have no idea how to make it sound nice.
  1 Comment
Image Analyst
Image Analyst on 11 Mar 2016
To make a natural sounding piece of music, you'll have to play a recording of an actual recording. I don't know how natural is "natural enough" for you but even with good synthesized music, a trained musician such as Itzhak Perlman would most probably be able to tell natural from synthesized.

Sign in to comment.


Khai Nguyen
Khai Nguyen on 31 May 2022
Hi
How I can create the geometry and material properties (which determines k & m) of an instrument body, a bridge, and one string (ex: A, D, G, or C), and develop a 2D, lump-mass model of this model on software MATLAB.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!