# ADSR 振幅包络

按下琴键，振幅上升到峰值，再回落至保持电平。按住时电平维持稳定。松开琴键后，振幅从当时的高度降到零。

## 试一试

按住琴键，等振幅稳定在 46% 后松开。再次按下，在上升途中提前松手，比较两次的尾音。

## 交互细节

线性起音后，振幅在 0.36 秒内降至 46%。释音从当前振幅开始，时长由滑块决定。声音需手动开启。开启减少动态效果后显示静态曲线。

## 各平台的操作方式

- iOS · 按住琴键按钮再抬起手指。拖动滑块可调节起音和释音时间。
- Android · 按住琴键按钮再抬起手指。拖动滑块可调节起音和释音时间。
- PC · 聚焦琴键按钮，按住空格或回车再松开，用方向键调节滑块。

## 适用场景

设计合成器音符的起音与尾音，或比较短音和持续音。

## 实现要求

> 按下琴键时先起音、再衰减，随后保持稳定的振幅。松手时从当前振幅进入释音。允许调节起音和释音时间，并通过曲线和声音对比。

## 来源与致谢

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

## 独立 HTML 示例

将以下代码保存为 HTML 文件，用浏览器打开即可离线体验。

```html
<!doctype html>
<html lang="zh-Hans" 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>
```
