How to create a melody ?

12 次查看(过去 30 天)
Célia Lejeune
Célia Lejeune 2020-11-28
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

回答(1 个)

Image Analyst
Image Analyst 2020-11-28
编辑:Image Analyst 2020-11-28
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.
  2 个评论
Célia Lejeune
Célia Lejeune 2020-11-28
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
Image Analyst 2020-11-28
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)?

请先登录,再进行评论。

Community Treasure Hunt

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

Start Hunting!

Translated by