-
-
Notifications
You must be signed in to change notification settings - Fork 319
/
Copy pathsound.ts
90 lines (84 loc) · 2.07 KB
/
sound.ts
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import { Capacitor } from '@capacitor/core'
import { SoundEffect } from 'capacitor-sound-effect'
import throttle from 'lodash-es/throttle'
import settings from './settings'
import { isForeground } from './utils/appMode'
let ctx = typeof(window.AudioContext) !== 'undefined' ? new AudioContext() : null
export default {
load(): Promise<void> {
return Promise.all([
loadSound('move'),
loadSound('capture'),
loadSound('explosion'),
loadSound('lowtime'),
loadSound('dong'),
loadSound('berserk'),
loadSound('clock'),
loadSound('confirmation'),
]).then(() => console.log('all sounds loaded.'))
},
resume(): void {
if (ctx != null) {
void ctx.close() // should be able to reuse these. However, webkit.
ctx = new AudioContext()
}
},
move(): void {
play('move')
},
throttledMove: throttle(() => {
play('move')
}, 50),
capture(): void {
play('capture')
},
throttledCapture: throttle(() => {
play('capture')
}, 50),
explosion(): void {
play('explosion')
},
throttledExplosion: throttle(() => {
play('explosion')
}, 50),
lowtime(): void {
play('lowtime')
},
dong(): void {
play('dong')
},
berserk(): void {
play('berserk')
},
clock(): void {
play('clock')
},
confirmation(): void {
play('confirmation')
},
}
const iosBuffers: {[id: string]: AudioBuffer } = {}
async function loadSound(id: string): Promise<void> {
const path = `sounds/${id}.mp3`
if (Capacitor.getPlatform() === 'ios' && ctx != null) {
window
.fetch(path)
.then(rsp => rsp.arrayBuffer())
.then(buf => ctx!.decodeAudioData(buf))
.then(audio => iosBuffers[id] = audio)
} else {
SoundEffect.loadSound({ id, path })
}
}
function play(id: string): void {
if (settings.general.sound() && isForeground()) {
if (Capacitor.getPlatform() === 'ios' && ctx != null) {
const mv = ctx.createBufferSource()
mv.buffer = iosBuffers[id]
mv.connect(ctx.destination)
mv.start()
} else {
SoundEffect.play({ id })
}
}
}