# Help using ADSR with 'linspace'

15 views (last 30 days)
Kyle Weaver on 7 Jul 2021
Answered: Prabhan Purwar on 27 Jul 2021
I have created a MATLAB code to create a sound that is the first few notes of twinkle twinkle little star. I was wondering if someone would be able to help me figure out how to properly use the ADSR model. I have included the code and am having a lot of difficulty making an ADSR that works. Any help or resources would be greatly appreciated.
Code:
>> Fs = 4000; %sampling frequency for one count
>>
>> A = 440; %frequency for A
>> C = 220 * 2^(3/12); %frequency for C
>> G = 220 * 2^(10/12); %frequency for G
>>
>> t1=0:1/Fs:1; %1 counts
>> t2=0:1/Fs:2; %2 counts
>> t3=0:1/Fs:4; %4 counts
>> p=zeros(1,1000); %Pause in between each note being played
>>
>> note_A2 = sin(2*pi*A*t2); %note A with 2 count pause
>> note_C = sin(2*pi*C*t1); %note C with 1 count pause
>> note_G = sin(2*pi*G*t1); %note G with 1 count pause
>> note_A = sin(2*pi*A*t1); %note A with 1 count pause
>> note_G2 = sin(2*pi*G*t2); %note G with 2 count pause
>>
>> x = [note_C p note_C p note_G p note_G p note_A p note_A p note_G2]; %twinkle twinkle little star
>>
>> sound(x, 8000); %playing sound with 8 kHz sample rate

Prabhan Purwar on 27 Jul 2021
Hi,
Kindly have a look at the following ADSR implementation code:
clear
fs = 4000; %sampling frequency for one count
% Node frequency
A = 440; %frequency for A
C = 220 * 2^(3/12); %frequency for C
G = 220 * 2^(10/12); %frequency for G
% target - vector of attack, sustain, release target values
% gain - vector of attack, sustain, release gain values
% duration - vector of attack, sustain, release durations in ms
target = [0.99999;0.25;0];
gain = [0.005;0.0004;0.00075];
duration = [125;625;250];
t1=linspace(0,1,fs);% counts
t2=linspace(0,1,fs); %2 counts
t3=linspace(0,1,fs); %4 counts
p=zeros(1,100); %Pause in between each note being played
note_A2 = sin(2*pi*A*t2); %note A with 2 count pause
note_C = sin(2*pi*C*t1); %note C with 1 count pause
note_G = sin(2*pi*G*t1); %note G with 1 count pause
note_A = sin(2*pi*A*t1); %note A with 1 count pause
note_G2 = sin(2*pi*G*t2); %note G with 2 count pause
duration = round(duration./1000.*fs);
% Attack phase
start = 2;
stop = duration(1);
for n = start:stop
end
% Sustain phase
start = stop + 1;
stop = start + duration(2);
for n = start:stop
end
% Release phase
start = stop + 1;
stop = fs;
for n = start:stop
end
% Avoid playback distortion
y = y ./ max(abs(y)); % Normalize samples
sound(y,fs);
Kindly tune the parameters for pleasing sound.
Hope it helps!!

### Categories

Find more on Hilbert and Walsh-Hadamard Transforms in Help Center and File Exchange

R2020b

### Community Treasure Hunt

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

Start Hunting!