-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSample.js
More file actions
73 lines (64 loc) · 2.14 KB
/
Copy pathSample.js
File metadata and controls
73 lines (64 loc) · 2.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/**
* Author and copyright: Stefan Haack (https://shaack.com)
* Repository: https://github.com/shaack/cm-web-modules
* License: MIT, see file 'LICENSE'
*/
import {Audio} from "./Audio.js"
export class Sample {
constructor(src, props = {}) {
this.src = src
this.props = {
gain: 1,
loop: false,
startWithoutAudioContext: true // start to play, without enabled audio context
}
Object.assign(this.props, props)
this.gainNode = Audio.context().createGain()
this.gainNode.connect(Audio.destination())
this.setGain(this.props.gain)
this.audioBuffer = null
this.source = null
this.load()
}
setGain(gain) {
if(window.cmAudioDebug) {
console.log("Sample.setGain", gain)
}
this.gainNode.gain.setValueAtTime(gain, Audio.context().currentTime)
}
play(when = undefined, offset = undefined, duration = undefined) {
if(window.cmAudioDebug) {
console.log("Sample.play", this.src, when, offset, duration)
}
if (this.props.startWithoutAudioContext || Audio.isEnabled()) {
this.loading.then(() => {
this.source = this.createBufferSource()
this.source.loop = this.props.loop
this.source.start(when, offset, duration)
})
}
}
stop(when = undefined) {
if(window.cmAudioDebug) {
console.log("Sample.stop", this.src, when)
}
if (this.source) {
this.source.stop(when)
this.source = null
}
}
createBufferSource() {
const source = Audio.context().createBufferSource()
source.buffer = this.audioBuffer
source.connect(this.gainNode)
return source
}
load() {
this.loading = fetch(this.src)
.then(response => response.arrayBuffer())
.then(buffer => Audio.context().decodeAudioData(buffer))
.then(audioBuffer => { this.audioBuffer = audioBuffer })
.catch(() => { console.error("error loading sound", this.src) })
return this.loading
}
}