|
2 | 2 |
|
3 | 3 | This code monkey patches AudioParams with a method to get values at any time
|
4 | 4 |
|
5 |
| -## install |
| 5 | +## Getting started |
| 6 | + |
| 7 | +### Install |
6 | 8 |
|
7 | 9 | `npm i audioparam-getvalueattime`
|
8 | 10 |
|
| 11 | +### Example |
| 12 | + |
| 13 | + |
| 14 | +```javascript |
| 15 | +import 'audioparam-getvalueattime' |
| 16 | + |
| 17 | +// if you interrupt a schedulement with cancelAndHoldAtTime, |
| 18 | +// then you can continue from there with new events, e.g. ramps |
| 19 | +// but if there was nothing scheduled, then it will try to run your ramp from |
| 20 | +// the end of a last event |
| 21 | +const properCancelAndHold = (node, time) => { |
| 22 | + if (node.hasScheduledChangesAtTime(time)) { |
| 23 | + node.cancelAndHoldAtTime(time) |
| 24 | + } else { |
| 25 | + const valueAtTime = node.getValueAtTime(time) |
| 26 | + node.setValueAtTime(valueAtTime, time) |
| 27 | + } |
| 28 | +} |
| 29 | + |
| 30 | +const ctx = new AudioContext() |
| 31 | +const volume = ctx.createGain() |
| 32 | +const oscillator = ctx.createOscillator() |
| 33 | + |
| 34 | +// ... |
| 35 | + |
| 36 | +const attack = 0.1 |
| 37 | +const release = 0.3 |
| 38 | + |
| 39 | +const scheduleNoteOn = (pitch, velocity, t) => { |
| 40 | + const gain = volume.gain |
| 41 | + const frequency = oscillator.frequency |
| 42 | + properCancelAndHold(gain, t) |
| 43 | + gain.linearRampToValueAtTime(velocity, t + attack) |
| 44 | + frequency.setValueAtTime(pitch, t) |
| 45 | +} |
| 46 | + |
| 47 | +const scheduleNoteOff = (t) => { |
| 48 | + const gain = volume.gain |
| 49 | + properCancelAndHold(gain, t) |
| 50 | + gain.linearRampToValueAtTime(0, t + release) |
| 51 | +} |
| 52 | + |
| 53 | +// ... |
| 54 | + |
| 55 | +const startTime = ctx.currentTime |
| 56 | + |
| 57 | +scheduleNoteOn(440, 0.5, startTime) |
| 58 | +scheduleNoteOff(startTime + 1) |
| 59 | + |
| 60 | +scheduleNoteOn(550, 0.5, startTime + 2) |
| 61 | +scheduleNoteOff(startTime + 3) |
| 62 | + |
| 63 | +scheduleNoteOn(660, 0.5, startTime + 2.5) |
| 64 | +scheduleNoteOff(startTime + 3.5) |
| 65 | + |
| 66 | +``` |
| 67 | + |
9 | 68 | ## API
|
10 | 69 |
|
| 70 | +The lib has no exports, since it's an IIFE, that will automatically run and patch up the native AudioContext |
| 71 | + |
| 72 | +The following methods will become available on AudioParam instances: |
| 73 | + |
11 | 74 | `AudioParam.prototype.getValueAtTime(t)` - calculates the value at `t` time based on scheduled changes
|
12 | 75 |
|
13 | 76 | `AudioParam.prototype.hasScheduledChangesAtTime(t)` - checks whether there are any changes scheduled at or after `t` time
|
|
0 commit comments