Skip to content

Commit f40d175

Browse files
docs(readme): added example
1 parent f31658b commit f40d175

File tree

1 file changed

+64
-1
lines changed

1 file changed

+64
-1
lines changed

Diff for: README.md

+64-1
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,75 @@
22

33
This code monkey patches AudioParams with a method to get values at any time
44

5-
## install
5+
## Getting started
6+
7+
### Install
68

79
`npm i audioparam-getvalueattime`
810

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+
968
## API
1069

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+
1174
`AudioParam.prototype.getValueAtTime(t)` - calculates the value at `t` time based on scheduled changes
1275

1376
`AudioParam.prototype.hasScheduledChangesAtTime(t)` - checks whether there are any changes scheduled at or after `t` time

0 commit comments

Comments
 (0)