# ADSR amplitude envelope

Press the key to raise the amplitude to its peak, then let it settle at the sustain level. Hold to maintain that level. Releasing the key takes the current amplitude down to zero.

## Try it

Hold the key until the amplitude settles at 46%, then release. Try again and let go during the rise to compare the tails.

## Interaction details

A linear attack is followed by a 0.36-second decay to 46%. Release runs from the current amplitude for the chosen time. Audio is opt-in. Reduced motion shows a stationary diagram.

## Platform controls

- iOS · Hold the key button, then lift your finger. Drag the sliders to change attack and release.
- Android · Hold the key button, then lift your finger. Drag the sliders to change attack and release.
- PC · Focus the key button, hold Space or Enter, then release. Adjust the sliders with the arrow keys.

## Where to use it

Shape the onset and tail of a synthesizer note or compare short and sustained notes.

## Implementation prompt

> On key down, run attack and decay before sustaining the amplitude. On key up, start release at the current amplitude. Let me adjust attack and release and compare the graph with the sound.

## Sources and credits

[Ableton · Learning Synths](<https://learningsynths.ableton.com/en/envelopes/modulating-amplitude-with-envelopes>)

## Standalone HTML

Save the code below as an HTML file and open it in your browser. The example works offline.

```html
<!doctype html>
<html lang="en" data-motion-locales="inline">
<head><script>if(new URLSearchParams(location.search).get('reduce')==='1')document.documentElement.classList.add('motion-reduced');</script><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>건반 하나의 음량 곡선</title>
<style>
*{box-sizing:border-box}:root{font:15px/1.4 system-ui,sans-serif;color:#f4e6d4;background:#201b29;color-scheme:dark}body{margin:0;min-height:100svh;display:grid;align-content:center;padding:clamp(12px,3vw,26px)}main{width:min(100%,710px);margin:auto}header,.display,.tools,.slider-label,.panel{display:flex;align-items:center;gap:8px}header,.display,.slider-label,.tools{justify-content:space-between}header{margin-bottom:10px;flex-wrap:wrap}h1{font:550 clamp(22px,4.4vw,34px)/1.1 Georgia,serif;letter-spacing:-.035em;margin:0}header small,.display,.slider-label{font-weight:650;font-size:clamp(10px,2vw,13px)}.scope{border:1px solid #685668;border-radius:9px;padding:8px 12px 3px;background:#2c2433}.display{color:#f9cea4}.readout{font-variant-numeric:tabular-nums;color:#dcbed9}#plot{display:block;width:100%;height:auto;aspect-ratio:640/177}#plot text{font:600 13px system-ui,sans-serif;fill:#e5d7d1}#plot .small{font-size:11px;fill:#c4b0bb}#plot line{vector-effect:non-scaling-stroke}.panel{margin-top:10px;align-items:stretch;gap:10px}.params{display:grid;grid-template-columns:1fr 1fr;gap:14px;flex:1;min-width:0;border:1px solid #645568;padding:8px 12px;background:#2c2433;border-radius:8px}label{min-width:0;display:block}output{font-variant-numeric:tabular-nums;white-space:nowrap}input{display:block;width:100%;margin:6px 0 0;accent-color:#efaa7b}.tools{gap:7px;flex-wrap:wrap;justify-content:flex-start}button{cursor:pointer;color:#f6e8db;border:1px solid #7c6b7d;background:#382f40;border-radius:7px;padding:8px 11px;font:650 13px/1.2 system-ui,sans-serif;min-height:38px}#gate{touch-action:none;user-select:none;-webkit-user-select:none;background:#f0b887;border-color:#f0b887;color:#322535;box-shadow:0 3px #805e64;min-width:135px}#gate[aria-pressed="true"]{background:#f9d5a4;box-shadow:0 1px #805e64;transform:translateY(2px)}button:focus-visible,input:focus-visible{outline:2px solid #ffe5a4;outline-offset:3px}.foot{display:flex;justify-content:space-between;align-items:center;gap:8px;margin-top:9px}.hint{margin:0;font-size:clamp(11px,1.8vw,13px);color:#d3c0ce}.foot button{flex-shrink:0;min-height:32px;font-size:11px}#sound[aria-pressed="true"]{color:#ffc583}
@media(max-width:520px){.panel{flex-wrap:wrap}.params{flex-basis:100%}#gate{width:100%}.tools{width:100%}.scope{padding:6px}#plot{min-height:118px}.foot{align-items:flex-start}.foot button{padding:5px 7px}.panel{gap:6px}}
</style></head><body><main>
<header><h1 data-t="title"></h1><small data-t="instrument"></small></header>
<section class="scope"><div class="display"><span data-t="amp"></span><span class="readout"><span id="phase"></span> · <output id="level">0%</output></span></div>
<svg id="plot" viewBox="0 0 640 177" preserveAspectRatio="none" role="img">
<g stroke="#4d3f50" stroke-width="1" fill="none"><path d="M30 25H629M30 56H629M30 87H629M30 118H629M30 149H629 M30 14V149"/></g>
<g id="bars"></g><path id="fill" fill="#c78971" opacity=".20"></path><path id="guide" fill="none" stroke="#be9eae" stroke-width="2" stroke-dasharray="5 4"></path><path id="trace" fill="none" stroke="#ffc18f" stroke-width="3" stroke-linejoin="round"></path><circle id="marker" r="4.5" fill="#fff2c6" stroke="#5b3a43" stroke-width="2"></circle>
<g><text x="3" y="28" class="small">1.0</text><text x="5" y="151" class="small">0</text><text x="30" y="172" class="small">0 s</text><text id="timespan" x="629" y="172" text-anchor="end" class="small"></text></g></svg></section>
<div class="panel"><div class="params"><label for="attack"><span class="slider-label"><span data-t="attack"></span><output id="attackval"></output></span><input id="attack" type="range" min="100" max="1000" step="50" value="450"></label><label for="release"><span class="slider-label"><span data-t="release"></span><output id="releaseval"></output></span><input id="release" type="range" min="150" max="1400" step="50" value="700"></label></div>
<div class="tools"><button type="button" id="gate" aria-pressed="false" data-t="gate"></button></div></div>
<div class="foot"><p class="hint" data-t="hint"></p><button id="sound" type="button" aria-pressed="false"></button></div>
</main><script>
const strings={
 ko:{title:'건반 하나의 음량 곡선',instrument:'ADSR 신시사이저',amp:'진폭',attack:'A · 상승 시간',release:'R · 해제 시간',gate:'건반 길게 누르기',hint:'건반을 누른 채 기다렸다가 놓으세요. 두 슬라이더로 시작과 끝의 길이를 바꿀 수 있어요.',off:'소리 꺼짐',on:'소리 켜짐',stages:['대기','상승','감쇠','유지','해제'],plot:'건반을 누르고 놓을 때 시간에 따라 변하는 진폭'},
 en:{title:'The shape of one note',instrument:'ADSR synthesizer',amp:'Amplitude',attack:'A · Attack',release:'R · Release',gate:'Hold the key',hint:'Hold the key, then let go. Adjust the sliders to reshape the beginning and end of the note.',off:'Sound off',on:'Sound on',stages:['Ready','Attack','Decay','Sustain','Release'],plot:'Amplitude over time as the note is held and released'},
 es:{title:'La forma de una nota',instrument:'Sintetizador ADSR',amp:'Amplitud',attack:'A · Ataque',release:'R · Liberación',gate:'Mantén la tecla',hint:'Mantén la tecla pulsada y suéltala. Ajusta los controles para cambiar el inicio y el final de la nota.',off:'Sonido apagado',on:'Sonido activo',stages:['Listo','Ataque','Decaimiento','Sostenimiento','Liberación'],plot:'Amplitud en el tiempo mientras se mantiene y suelta la tecla'},
 'zh-Hans':{title:'一个音符的音量曲线',instrument:'ADSR 合成器',amp:'振幅',attack:'A · 起音时间',release:'R · 释音时间',gate:'按住琴键',hint:'按住琴键，稍等片刻再松开。拖动滑块可改变音符开始与结束的时长。',off:'声音已关',on:'声音已开',stages:['待机','起音','衰减','保持','释音'],plot:'按住和松开琴键时，振幅随时间变化的曲线'}
};
const params=new URLSearchParams(location.search),root=document.documentElement,requested=params.get('lang')||root.lang;
const lang=Object.hasOwn(strings,requested)?requested:'ko',t=strings[lang];root.lang=lang;document.title=t.title;
document.querySelectorAll('[data-t]').forEach(el=>el.textContent=t[el.dataset.t]);
const by=id=>document.getElementById(id),gate=by('gate'),a=by('attack'),r=by('release'),sound=by('sound');
const media=matchMedia('(prefers-reduced-motion: reduce)'),S=.46,D=.36;
let held=false,start=0,releasedAt=null,frame=0,complete=false,voice=null,ctx=null,sounding=false,ready=true;
const reduce=()=>params.get('reduce')==='1'||root.classList.contains('motion-reduced')||media.matches;
const elapsed=()=>Math.max(0,(performance.now()-start)/1000);
const attack=()=>Number(a.value)/1000,release=()=>Number(r.value)/1000;
const num=value=>new Intl.NumberFormat(lang,{minimumFractionDigits:2,maximumFractionDigits:2}).format(value);
function onGate(time){if(time<=attack())return time/attack();if(time<attack()+D)return 1-(1-S)*(time-attack())/D;return S}
function amplitude(time,end){return time<=end?onGate(time):onGate(end)*Math.max(0,1-(time-end)/release())}
function phase(time,end){return time>=end+release()?0:time>=end?4:time<attack()?1:time<attack()+D?2:3}
function render(){
 const previewEnd=attack()+D+.58;
 const current=ready?0:elapsed(),end=releasedAt??Math.max(previewEnd,current+.05);
 const duration=end+release(),x=v=>30+599*v/duration,y=v=>149-124*v;
 const mapPoint=v=>x(v).toFixed(2)+' '+y(amplitude(v,end)).toFixed(2);
 const times=[...new Set([0,...[attack(),attack()+D].filter(v=>v<end),end,duration])];
 const plot=by('plot');plot.setAttribute('aria-label',t.plot);plot.dataset.gate=held?'held':ready?'ready':complete?'complete':'released';
 const staticMode=reduce(),time=ready?0:staticMode?(held?Math.min(end,attack()+D):duration):Math.min(current,duration);
 const level=amplitude(time,end),stage=ready?0:staticMode&&held?3:phase(time,end);
 by('phase').textContent=t.stages[stage];by('level').textContent=Math.round(level*100)+'%';plot.dataset.level=level.toFixed(3);plot.dataset.phase=String(stage);
 const full='M'+times.map(mapPoint).join(' L');
 by('guide').setAttribute('d',full);
 const drawn=ready||staticMode||complete?times:[...times.filter(v=>v<time),time];const trace='M'+drawn.map(mapPoint).join(' L');
 by('trace').setAttribute('d',trace);by('fill').setAttribute('d',trace+' L'+x(drawn[drawn.length-1])+' 149 Z');
 by('marker').setAttribute('cx',x(time));by('marker').setAttribute('cy',y(level));by('timespan').textContent=num(duration)+' s';
 const points=[0,Math.min(attack(),end),Math.min(attack()+D,end),end,duration];
 by('bars').innerHTML=points.slice(1).map((p,i)=>{const left=x(points[i]),right=x(p);if(right-left<17)return '';return '<text x="'+((left+right)/2)+'" y="16" text-anchor="middle">'+['A','D','S','R'][i]+'</text><line x1="'+right+'" y1="23" x2="'+right+'" y2="149" stroke="#5d4a5c" stroke-dasharray="2 4"/>'}).join('');
 by('attackval').textContent=num(attack())+' s';by('releaseval').textContent=num(release())+' s';
}
function tick(){cancelAnimationFrame(frame);if(!held&&releasedAt!==null&&(reduce()||elapsed()>=releasedAt+release()))complete=true;render();if(!ready&&!complete&&!reduce())frame=requestAnimationFrame(tick)}
function stopVoice(){if(!voice)return;const active=voice;voice=null;active.gain.disconnect();active.osc.stop()}
function beginVoice(){
 if(!sounding||!ctx)return;stopVoice();const osc=ctx.createOscillator(),gain=ctx.createGain(),now=ctx.currentTime;
 osc.type='sine';osc.frequency.value=196;gain.gain.value=0;osc.connect(gain);gain.connect(ctx.destination);
 const active={osc,gain};osc.onended=()=>{osc.disconnect();gain.disconnect();if(voice===active)voice=null};
 gain.gain.setValueAtTime(0,now);gain.gain.linearRampToValueAtTime(.12,now+attack());gain.gain.linearRampToValueAtTime(.12*S,now+attack()+D);osc.start();voice=active;
}
function begin(){if(held)return;held=true;complete=false;ready=false;releasedAt=null;start=performance.now();gate.setAttribute('aria-pressed','true');beginVoice();tick()}
function end(){
 if(!held)return;held=false;releasedAt=elapsed();gate.setAttribute('aria-pressed','false');
 if(voice){const {osc,gain}=voice,now=ctx.currentTime;gain.gain.cancelScheduledValues(now);gain.gain.setValueAtTime(.12*onGate(releasedAt),now);gain.gain.linearRampToValueAtTime(0,now+release());osc.stop(now+release()+.02)}
 tick();
}
function adjust(){if(held)end();stopVoice();cancelAnimationFrame(frame);ready=true;complete=false;releasedAt=null;render()}
[a,r].forEach(el=>el.addEventListener('input',adjust));
gate.addEventListener('pointerdown',e=>{if(e.button!==0)return;gate.focus();gate.setPointerCapture(e.pointerId);begin()});
['pointerup','pointercancel','lostpointercapture','blur'].forEach(name=>gate.addEventListener(name,end));
gate.addEventListener('keydown',e=>{if(e.key===' '||e.key==='Enter'){e.preventDefault();if(!e.repeat)begin()}});
gate.addEventListener('keyup',e=>{if(e.key===' '||e.key==='Enter'){e.preventDefault();end()}});
gate.addEventListener('click',e=>{if(e.detail===0){if(held)end();else begin()}});
window.addEventListener('blur',end);document.addEventListener('visibilitychange',()=>{if(document.hidden)end()});
function showSound(){sound.setAttribute('aria-pressed',String(sounding));sound.textContent=sounding?t.on:t.off}
sound.addEventListener('click',async()=>{const Audio=window.AudioContext||window.webkitAudioContext;if(!Audio)return;
 sounding=!sounding;showSound();
 if(sounding){ctx=ctx||new Audio();try{await ctx.resume()}catch{sounding=false;stopVoice();showSound()}}
 else{stopVoice();await ctx.suspend()}
});showSound();
media.addEventListener('change',tick);render();
</script></body></html>
```
