# How to create a melody ?

3 views (last 30 days)
Célia Lejeune on 28 Nov 2020
Commented: Image Analyst on 28 Nov 2020
Hello,
We are asked to make a melody with the different keys given that I place in the vector Num.
The problem is that the sound is not correct and I can't make it works so I am not able to recognize the melody. Each key needs to last 0.3.
Here is my code
Num=[40 42 44 40 0 40 42 44 40 0 44 45 47 0 44 45 47 0];
dur=0.3;
fs=48000;
A=1;
t = 0:1/fs:dur;
f=zeros(length(Num),0);
y=zeros(length(t),0);
for i=1:length(Num)
f(i)= 440*2^(((Num(i))-49)/12);
y= A*cos(2*pi*f(i)*1/dur);
soundsc(y,fs)
end
Could you help me or say what is wrong ?
Célia

Image Analyst on 28 Nov 2020
Edited: Image Analyst on 28 Nov 2020
Well first of all, your y is a single number - a scalar - not a complete waveform as it should be when passed into soundsc(). Then you need to put the soundsc() outside of the loop so it plays the whole waveform, not just one number. next, your formula for the cosine wave is not right. It should be cos(2 * pi * omega * time).
Here's some more. Zoom in on the y plot so you can see it has the correct time-varying frequency.
Num=[40 42 44 40 0 40 42 44 40 0 44 45 47 0 44 45 47 0];
dur= 2.3;
fs=48000;
A=1;
t = 0:1/fs:dur;
Num = interp1(0:length(Num)-1, Num, t, 'nearest');
f = zeros(length(Num),0);
y = zeros(length(Num),0);
for i=1:length(Num)
f(i) = 440*2^(((Num(i))-49)/12);
% y(i) = A*cos(2*pi*f(i)*1/dur);
y(i) = A*cos(2*pi*f(i)*i);
end
subplot(3, 1, 1);
plot(Num, 'r-');
grid on;
subplot(3, 1, 2);
plot(f, 'g-');
grid on;
subplot(3, 1, 3);
plot(y, 'b-');
grid on;
soundsc(y,fs)
Of course you could vectorize it and get rid of the for loop like this:
f = 440 * 2 .^ ((Num-49)/12);
y = A*cos(2 * pi * f .* i);
See my attached script that creates a signal and makes a wav file out of it. Adapt as needed.

Célia Lejeune on 28 Nov 2020
I tested the code but it still doesn't work in the cosinus I replace i by the time t and even if I get rid of the loop I can't hear anything.
Image Analyst on 28 Nov 2020
Well 48 kHz is way beyond the range of human hearing, and even speakers, so you may hear a click at best. Did you try to follow my demo (for a working example)?