Translate a music sheet into MATLAB code

32 次查看(过去 30 天)
I want to play a music sheet in MATLAB. I have seen some tutorials and threads but they only play one note at a time. How can I play 3 consecutive notes (a chord ex. C major composing notes C-E-G)? And also, how can I put rest in between notes? Can you give me sample code that I can use, or help me improve my code below?
% This will be on a separate file that define keys and duration
function tone = note(key,dur);
fs = 44100;
t = 0 : 1/fs : dur;
freq = 440 * 2 ^ ((key - 49) / 12);
wave = sin(2*pi*freq*t).* exp(-0.0004 * 2 * pi * freq * t) / 1;
if dur == 4
tone = wave.*(exp(-1.2*t));
elseif dur == 3
tone = wave.*(exp(-1.9*t));
elseif dur == 2.5
tone = wave.*(exp(-2.2*t));
elseif dur == 2.25
tone = wave.*(exp(-2.4*t));
elseif dur == 2
tone = wave.*(exp(-2.5*t));
elseif dur == 1.5
tone = wave.*(exp(-2.7*t));
elseif dur == 1.25
tone = wave.*(exp(-2.8*t));
elseif dur == 1
tone = wave.*(exp(-3*t));
elseif dur == 0.75
tone = wave.*(exp(-4*t));
elseif dur == 0.5
tone = wave.*(exp(-6*t));
elseif dur == 0.25
tone = wave.*(exp(-9*t));
end
end
I managed to play the 1st measure of the song of my choice, "When I was your man" by Bruno Mars.
%1st Measure
c10 = note(34,2) + note(37,2) + note(40,2);
c11 = note(33,2) + note(37,2) + note(40,2);
c12 = note(18,2) + note(30,2);
t01 = [c10 c11];
b01 = [c12 c12];
m1 = [t01 + b01];
soundsc(m1,44100);

采纳的回答

Cris LaPierre
Cris LaPierre 2021-10-15
In music, notes are just sine waves at a specific frequency played for a specific amount of time. Any quiet time can be achieved by pausing your code for the amount of time needed. This includes pausing your code while each note is played. The steps might be
  • Define your note frequencies
  • Organize your notes into a song
  • Define your timing
  • Define your pauses
  • Use a loop to play your notes in the order you defined, for the duration you defined, pausing as defined as well.
Below is an example for the song Happy Birthday. Remember that amplitude corresponds to volume. I am reducing the volume below by multiplying the sine wave by 0.25.
To play a chord, create a single sinusoid by adding the corresponding notes' sine waves together.
If you are interetsed in learning a little more about this, consider looking through our Bytes and Beats courseware material. The material is designed for young kids learning to program, but it may be helpful.
Fs = 8000;
Ts = 1/Fs;
% define notes used in song
G4 = 392;
A4 = 440;
C5 = 523.3;
B4 = 493.9;
D5 = 587;
G5 = 784;
F5 = 698.5;
E5 = 659;
% Organize notes/timing into the song
notes = [G4 G4 A4 G4 C5 B4];
duration = [0.3 0.1 0.4 0.4 0.4 0.4];
p = [0.3 0.1 0.4 0.4 0.4 0.8];
% Play
for loop = 1:length(notes)
% define sine wave
t = 0:Ts:duration(loop);
S = sin(2*pi*notes(loop)*t);
sound(0.25*S,Fs);
pause(p(loop));
end

更多回答(0 个)

Community Treasure Hunt

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

Start Hunting!

Translated by