# create a piece of music using matlab??

조회 수: 795(최근 30일)
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.

#### 댓글 수: 2

Passband Modulation 21 Sep 2012
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 21 Sep 2012
In grad school I figured out how to play every Linkin Park song:
sound(rand(100000,1),20000)

로그인 to comment.

### 답변 수 (7)

Star Strider 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)

#### 댓글 수: 4

표시 이전 댓글 수: 1
Walter Roberson 15 Apr 2019
Dylan Vizcarra 24 Nov 2019
Can you explain how the value 8192 was derived. Thank you
Star Strider 24 Nov 2019
@Dylan Vizcarra — At the time (seven years ago), it was the default sampling frequency for sound and soundsc.

로그인 to comment.

Ryan Black 27 Dec 2017
Ryan Black 님이 편집함. 6 Oct 2019
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 Discreet 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

#### 댓글 수: 7

표시 이전 댓글 수: 4
Star Strider 30 Dec 2017
I will.
It seems you’re already doing relatively sophisticated coding, though.
Ryan Black 20 Mar 2018
I am finishing up MATLAB MUSIC GUI (Sound Sampling/Recognition/Synthesis/Sequencing suite) and will put it on the file exchange when complete, clean, and user-friendly (hopefully 1-3 months)! In the meantime, interested people can preview the remodeled "Fully-Transient Master Wave Equation" I published above.
@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:

로그인 to comment.

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

#### 댓글 수: 0

로그인 to comment.

Wayne King 21 Sep 2012
Wayne King 님이 편집함. 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)

#### 댓글 수: 3

Franklin 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.
Jonas Törne 27 May 2018
Could you explain what sig=reshape(x',6*length(t),1); means? What does it do and why?
Walter Roberson 27 May 2018
The frequencies are defined across rows, one row per note. x' flips that so that they are down columns, one column per note. reshape() with final component 1 rearranges that into a single column vector -- so all of the samples of the first note, then all of the samples of the second note, and so on.
The more general method would be to use:
x = cos(2*pi*notes*t) .';
sig = x(:);

로그인 to comment.

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!

#### 댓글 수: 0

로그인 to comment.

Aurelija V 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

Image Analyst 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.

로그인 to comment.

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)

#### 댓글 수: 0

로그인 to comment.

이 질문에 답변하려면 로그인을(를) 수행하십시오.