Web Audio APIで電子ピアノ(5) : ADSR(Attack, Decay, Sustain, Release)

こちらのページの電子ピアノで鍵盤を押したときとリリースしたとき (マウスやタッチパネルでボタン押し操作を止めたとき) にADSR(Attack, Decay, Sustain, Release)のパラメータにしたがってゲインが変化するよう変更しました。

# Windows 11のPCのChromeとEdgeではほぼ安定して動作しますが、スマートフォンでボタンを二回連続で押したとき等の動作が不安定なことを確認しています。

Envelope
Attack:
(Time)
0% 100% Release:
(Time)
0% 100%
Decay:
(Time)
0% 100% Time
Scale:
0.0(s) 2.0(s)
Sustain:
(Volume)
0% 100%
Envelope
Attack:
(Time)
0%100%
Decay:
(Time)
0%100%
Sustain:
(Volume)
0%100%
Release:
(Time)
0%100%
Time
Scale:
0.0(s)2.0(s)
Volume: Mute100%
Current waveform:
Volume:
Current waveform:

ADSR(Attack, Decay, Sustain, Release)のパラメータはEnvelopeの枠の中のスライダーを操作して変更します。

  • Attack 鍵盤を押し始めてからゲインが最大になるまでの時間を指定します。Time Scaleのスライダーで指定する時間の長さにAttackで指定する割合を掛けた時間の長さをAttackの長さとしています。
  • Decay Attackで指定した長さが経過してゲインが最大になってからSustainで指定したゲインの大きさまで減少していく際の時定数の大きさを指定します。Time Scaleのスライダーで指定する時間の長さにDecayで指定する割合を掛けた時間の長さをDecayの時定数の大きさとしています。
  • Sustain 鍵盤を長押ししたときのゲインの大きさを指定します。AttackとDecay後のゲインの大きさになります。Volumeのスライダーで指定するゲインの最大値にSustainで指定する割合を掛けたゲインの大きさが鍵盤を長押ししたときのゲインの大きさになります。Attack、Decay、Releaseは時間の長さを指定しますが、Sustainはゲインの大きさを指定します。
  • Release 鍵盤をリリースしてから音が消えるまでの時間の長さを指定します。Time Scaleのスライダーで指定する時間の長さにReleaseで指定する割合を掛けた時間の長さをReleaseの長さとしています。

1. 鍵盤を押したときのゲインの時間変化を指定するコード

    gainNode.gain.setValueAtTime(0, t_pressed);
    gainNode.gain.linearRampToValueAtTime(volume, t_pressed + attackDuration);
    gainNode.gain.setTargetAtTime(sustainLevel * volume, t_pressed + attackDuration, decayDuration);

Attack、Decayまでのゲインの時間変化を指定しています。鍵盤を長押しすると、Decayの後、ゲインはSustainで指定した大きさになります。

  • gainNode.gain.setValueAtTime(0, t_pressed) でボタンを押したときのゲインの大きさに初期値0をセットしています。
  • gainNode.gain.linearRampToValueAtTime(volume, t_pressed + attackDuration) でAttackが経過した後のゲインの大きさをVolumeのスライダーでセットした大きさにしています。ゲインは0からvolumeまで時間に比例して変化するようにしています。
  • gainNode.gain.setTargetAtTime(sustainLevel * volume, t_pressed + attackDuration, decayDuration) でAttackとDecayが経過した後のゲインの大きさをSustainで指定した大きさに近付けます。ゲインは2つ目の引数 t_pressed + attackDuration で指定した時間から指数関数的に変化し、sustainLevel * volume に近付いていきます。
補足:ゲイン変化のスケジュール関数について

  • linearRampToValueAtTime(value, endTime)
    こちらのページに記載されているように下記の式にしたがってゲインを時間変化させます。

    \[v(t) = V_0 + (V_1 – V_0) \frac{t – T_0}{T_1 – T_0}\]

    上記の式で$T_0$は直前のイベントで指定された時刻、$V_0$は時刻$T_0$のゲインの大きさ、$T_1$は関数の引数endTimeで指定された時刻、$V_1$は関数の引数valueで指定されたゲインの大きさです。$T_0 \leq t < T_1$を満たす時刻$t$のゲインの大きさ$v(t)$を指定しています。$v(t)$は時間の経過とともに線形に変化します。

  • setTargetAtTime(target, startTime, timeConstant)
    こちらのページに記載されているように下記の式にしたがってゲインを時間変化させます。

    \[v(t) = V_1 + (V_0 – V_1) e^{-\frac{t – T_0}{\tau}}\]

    上記の式で$T_0$は関数の引数startTimeで指定するゲインの時間変化の開始時刻、$V_0$は時刻$T_0$のゲインの大きさ、$V_1$は関数の引数targetで指定する値、$\tau$は関数の引数timeConstantで指定する時定数です。$T_0 \leq t$を満たす時刻$t$のゲインの大きさ$v(t)$を指定しています。$v(t)$は時間の経過とともに指数関数にしたがって$V_1$に近付いていきます。

2. 鍵盤をリリースしたときのゲインの時間変化を指定するコード

    gainNode.gain.cancelScheduledValues(t_released);
    gainNode.gain.setValueAtTime(gainNode.gain.value, t_released);
    gainNode.gain.linearRampToValueAtTime(0, t_released + releaseDuration);
  • gainNode.gain.cancelScheduledValues(t_released) でボタンをリリースした時刻以降のゲインのスケジュールを取り消します。例えば、ボタンをリリースした時刻がAttackの時間が経過する前であれば、Attackの途中以降の処理とDecay、Sustainの処理が取り消されます。別の例では、ボタンを長押ししてSustainで指定したゲインの音が出力され続けていたときにリリースすると音を出力し続ける処理が取り消されます。
  • gainNode.gain.setValueAtTime(gainNode.gain.value, t_released) でボタンをリリースした時刻のゲインの大きさを再スケジュール開始時刻のゲインの大きさとしてセットしています。
  • gainNode.gain.linearRampToValueAtTime(0, t_released + releaseDuration) でReleaseで指定した時間が経過した後に音が消えるようにしています。ゲインの大きさは時間に比例して減少するようにしています。

3. 修正後のコード全体

3.1. css

<style type="text/css">
.container {
    overflow-x: scroll;
    overflow-y: hidden;
    width: 100%;
    height: 180px;
    white-space: nowrap;
    margin: 10px;
}

.keyboard {
    width: auto;
    padding: 0;
    margin: 0;
}

.key-set-parent {
    position: relative;
    display: inline-block;
    width: 40px;
    height: 120px;
}

.key {
    position: relative;
    cursor: pointer;
    font: 10px "Open Sans", "Lucida Grande", "Arial", sans-serif;
    border: 1px solid black;
    border-radius: 5px;
    width: 40px;
    height: 120px;
    text-align: center;
    box-shadow: 2px 2px darkgray;
    display: inline-block;
    margin-right: 3px;
    user-select: none;
    -moz-user-select: none;
    -webkit-user-select: none;
    -ms-user-select: none;
}

.key.black-key {
    position: absolute;
    background-color: #000;
    color: #fff;
    width: 36px;
    height: 80px;
    top: 0px;
    left: 22px;
    z-index: 1;
    pointer-events: auto;
    vertical-align: top;
}

.key div {
    position: absolute;
    bottom: 0;
    text-align: center;
    width: 100%;
    pointer-events: none;
}

.key div sub {
    font-size: 8px;
    pointer-events: none;
}

.key:hover {
    background-color: #eef;
}

.key.black-key:hover {
    background-color: #778;
}

.key:active {
    background-color: #000;
    color: #fff;
}

.key.black-key:active {
    background-color: #fff;
    color: #000;
}

.octave {
    display: inline-block;
    padding: 0 6px 0 0;
}

.settingsBar {
    padding-top: 8px;
    font: 14px "Open Sans", "Lucida Grande", "Arial", sans-serif;
    position: relative;
    vertical-align: middle;
    width: 100%;
    height: 60px;
}

.left {
    width: 50%;
    position: absolute;
    left: 0;
    display: table-cell;
    vertical-align: middle;
}

.left span, .left input {
    vertical-align: middle;
}

.right {
    width: 50%;
    position: absolute;
    right: 0;
    display: table-cell;
    vertical-align: middle;
}

.right span {
    vertical-align: middle;
}

.right input {
    vertical-align: baseline;
}

.envelope-fieldset {
    padding-top: 8px;
    position: relative;
    font: 18px "Open Sans", "Lucida Grande", "Arial", sans-serif;
    left: 0;
    display: table-cell;
    border-style: solid;
    vertical-align: middle;
    border-color: #000;
    background-color: #eee;
}

.table-border-none, .table-border-none td {
    font: 14px "Open Sans", "Lucida Grande", "Arial", sans-serif;
    left: 0;
    width: 45%;
    vertical-align: middle;
    white-space: nowrap;
    border: none;
}
</style>

3.2. HTML

<div class="container">
    <div class="keyboard"></div>
</div>

<fieldset class="envelope-fieldset">
    <legend>Envelope</legend>

    <table class="table-border-none">
        <tr>
            <td>Attack:<br/>(Time)</td>
            <td>0%</td>
            <td><input type="range" min="0.0" max="1.0" step="0.01" value="0.1" name="attack"></td>
            <td>100%</td>

            <td>Release:<br/>(Time)</td>
            <td>0%</td>
            <td><input type="range" min="0.0" max="1.0" step="0.01" value="0.5" name="release"></td>
            <td>100%</td>
        </tr>

        <tr>
            <td>Decay:<br/>(Time)</td>
            <td>0%</td>
            <td><input type="range" min="0.0" max="1.0" step="0.01" value="0.5" name="decay"></td>
            <td>100%</td>

            <td>Time<br/>Scale:</td>
            <td>0.0(s)</td>
            <td><input type="range" min="0.0" max="2.0" step="0.01" value="1.0" name="time-scale"></td>
            <td>2.0(s)</td>
        </tr>

        <tr>
            <td>Sustain:<br/>(Volume)</td>
            <td>0%</td>
            <td><input type="range" min="0.0" max="1.0" step="0.01" value="0.5" name="sustain"></td>
            <td>100%</td>

            <td></td>
            <td></td>
            <td></td>
            <td></td>
        </tr>
    </table>
</fieldset>

<div class="settingsBar">
    <div class="left">
        <table class="table-border-none">
            <tr>
                <td>Volume: </td>
                <td>Mute<input type="range" min="0.0" max="1.0" step="0.01" value="0.5" name="volume">100%</td>
            </tr>
        </table>
    </div>

    <div class="right">
        <span>Current waveform: </span>
        <select name="waveform">
            <option value="sine">Sine</option>
            <option value="square">Square</option>
            <option value="sawtooth">Sawtooth</option>
            <option value="triangle" selected>Triangle</option>
            <option value="custom">Custom</option>
        </select>
    </div>
</div>

3.3. JavaScript

<script>
const audioContext = new (window.AudioContext || window.webkitAudioContext)();

const oscillatorMap = new Map();
const gainNodeMap = new Map();

const keyboard = document.querySelector(".keyboard");
const wavePicker = document.querySelector("select[name='waveform']");
const volumeControl = document.querySelector("input[name='volume']");
const attackControl = document.querySelector("input[name='attack']");
const decayControl = document.querySelector("input[name='decay']");
const sustainControl = document.querySelector("input[name='sustain']");
const releaseControl = document.querySelector("input[name='release']");
const timeScaleControl = document.querySelector("input[name='time-scale']");

let noteFreq = null;
let customWaveform = null;
let sineTerms = null;
let cosineTerms = null;

const note_names =
[
    ["ラ", "", "A", ""],
    ["ラ#", "シ$\\flat$", "A#", "B$\\flat$"],
    ["シ", "","B", ""],
    ["ド", "","C", ""],
    ["ド#", "レ$\\flat$","C#", "D$\\flat$"],
    ["レ", "","D", ""],
    ["レ#", "ミ$\\flat$","D#", "E$\\flat$"],
    ["ミ", "","E", ""],
    ["ファ", "","F", ""],
    ["ファ#", "ソ$\\flat$","F#", "G$\\flat$"],
    ["ソ", "", "G", ""],
    ["ソ#", "ラ$\\flat$", "G#", "A$\\flat$"]
];

setup();

// -------------------------------------------------------
// functions
// -------------------------------------------------------

function createNoteTable() {

    let noteFreq = [];
    for (let octave = 0; octave < 9; octave++) {
        noteFreq[octave] = [];
    }

    for (let n = 0; n < 88; n++) {

        const frequency = getAudioFrequency(n);

        let octave = parseInt(n/12);
        if (n % 12 >= 3) {
            octave++;
        }

        const note_name_sharp_japanese = note_names[n % 12][0];
        noteFreq[octave][note_name_sharp_japanese] = frequency;
    }

    return noteFreq;
}

function getAudioFrequency(n) {
    return 27.5 * ( Math.pow( Math.pow(2, 1/12), n) );
}

function setup() {
    noteFreq = createNoteTable();

    noteFreq.forEach(function(keys, idx) {

        const keyList = Object.entries(keys);
        const octaveElem = document.createElement("div");
        octaveElem.className = "octave";

        for (let i = 0; i < keyList.length; i++) {

            const keySetElem = document.createElement("div");
            keySetElem.className = "key-set-parent";

            const whiteKey = keyList[i];
            const whiteKeyName = whiteKey[0];

            const whiteKeyElem = createKey(whiteKeyName, idx, whiteKey[1], 'white-key');
            keySetElem.appendChild(whiteKeyElem);

            if ( whiteKeyName === 'ド' || whiteKeyName === 'レ' || whiteKeyName === 'ファ' ||
                 whiteKeyName === 'ソ' || whiteKeyName === 'ラ') {

                const blackKey = keyList[++i];

                if (blackKey != undefined) {
                    const blackKeyName = blackKey[0];
                    const blackKeyElem = createKey(blackKeyName, idx, blackKey[1], 'black-key');
                    keySetElem.appendChild(blackKeyElem);
                }
            }

            octaveElem.appendChild(keySetElem);
        }

        keyboard.appendChild(octaveElem);
    });

    document.querySelector("div[data-note='ファ'][data-octave='5']").scrollIntoView(false);

    sineTerms = new Float32Array([0, 0, 1, 0, 1]);
    cosineTerms = new Float32Array(sineTerms.length);
    customWaveform = audioContext.createPeriodicWave(cosineTerms, sineTerms);
}

function createKey(note, octave, freq, keyColor) {
    const keyElement = document.createElement("div");
    const labelElement = document.createElement("div");

    if (keyColor === 'black-key') {
        keyElement.className = "key black-key";
    } else {
        keyElement.className = "key";
    }

    keyElement.dataset["octave"] = octave;
    keyElement.dataset["note"] = note;
    keyElement.dataset["frequency"] = freq;

    labelElement.innerHTML = note + "<sub>" + octave + "</sub>";
    keyElement.appendChild(labelElement);

    keyElement.addEventListener("mousedown", notePressed, false);
    keyElement.addEventListener("mouseup", noteReleased, false);
    keyElement.addEventListener("mouseleave", noteReleased, false);

    keyElement.addEventListener("touchstart", notePressed, false);
    keyElement.addEventListener("touchend", noteReleased, false);
    keyElement.addEventListener("touchmove", noteReleased, false);
    keyElement.addEventListener("touchcancel", noteReleased, false);

    return keyElement;
}

function notePressed(event) {

    event.preventDefault();

    const dataset = event.target.dataset;

    if (dataset["pressed"]) {
        return;
    }

    dataset["pressed"] = "yes";

    const octave = dataset["octave"];
    const note = dataset["note"];
    const frequency = dataset["frequency"];

    const oscillator = audioContext.createOscillator();

    const t_pressed = audioContext.currentTime;
    const volume = parseFloat(volumeControl.value);
    const timeScale = parseFloat(timeScaleControl.value);
    const attackDuration = parseFloat(attackControl.value) * timeScale;
    const decayDuration = parseFloat(decayControl.value) * timeScale;
    const sustainLevel = parseFloat(sustainControl.value);

    // Attack -> Decay -> Sustain
    const gainNode = audioContext.createGain();
    gainNode.connect(audioContext.destination);
    gainNode.gain.setValueAtTime(0, t_pressed);
    gainNode.gain.linearRampToValueAtTime(volume, t_pressed + attackDuration);
    gainNode.gain.setTargetAtTime(sustainLevel * volume, t_pressed + attackDuration, decayDuration);

    oscillator.connect(gainNode);

    const type = wavePicker.options[wavePicker.selectedIndex].value;

    if (type == "custom") {
        oscillator.setPeriodicWave(customWaveform);
    } else {
        oscillator.type = type;
    }

    oscillator.frequency.value = frequency;
    oscillator.start();

    const keyID = note + octave;
    oscillatorMap.set(keyID, oscillator);
    gainNodeMap.set(keyID, gainNode);
}

function noteReleased(event) {

    event.preventDefault();

    const dataset = event.target.dataset;

    if (!dataset["pressed"]) {
        return;
    }

    delete dataset["pressed"];

    const octave = dataset["octave"];
    const note = dataset["note"];
    const frequency = dataset["frequency"];
    const keyID = note + octave;

    const oscillator = oscillatorMap.get(keyID);
    const gainNode = gainNodeMap.get(keyID);

    const t_released = audioContext.currentTime;
    const timeScale = parseFloat(timeScaleControl.value);
    const releaseDuration = parseFloat(releaseControl.value) * timeScale;

    gainNode.gain.cancelScheduledValues(t_released);
    gainNode.gain.setValueAtTime(gainNode.gain.value, t_released);
    gainNode.gain.linearRampToValueAtTime(0, t_released + releaseDuration);

    oscillator.stop(t_released + releaseDuration);
}
</script>

Leave a Reply