-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlib.ts
93 lines (74 loc) · 2.36 KB
/
lib.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
91
92
93
import { initialize, sendCommand } from './index'
import EventEmitter from 'events'
export class RodioBackend extends EventEmitter {
#eventSender: Object
constructor() {
super()
const ret = initialize()
this.#eventSender = ret
if (!this.#eventSender || typeof ret !== 'object') {
throw new Error("Failed to initialize rodio backend")
}
this.on('timeUpdate', (pos) => {
if (this.totalDuration && pos >= this.totalDuration - 400) {
this.emit('ended')
}
})
}
private totalDuration: number | undefined = undefined
public async setSrc(path: string) {
const duration = await this.sendCommandAsync("SET_SRC", path)
this.totalDuration = duration
this.emit('loaded')
}
private sendCommandAsync(command: string, args?: string) {
return new Promise<number>((resolve, reject) => {
sendCommand(command, args ?? "", this.#eventSender, (err, ret) => {
if (err) {
reject(err)
}
resolve(ret)
})
})
}
public async play() {
await this.sendCommandAsync("PLAY")
this.initializePositionListener()
this.emit('play')
}
public async pause() {
await this.sendCommandAsync("PAUSE")
this.clearInterval()
this.emit('pause')
}
public async stop() {
await this.sendCommandAsync("STOP")
this.clearInterval()
this.emit('stop')
}
public setVolume(volume: number) {
return this.sendCommandAsync("SET_VOLUME", Math.max(Math.min(volume, 1), 0).toString())
}
public getVolume() {
return this.sendCommandAsync("GET_VOLUME")
}
public getPosition() {
return this.sendCommandAsync("GET_POSITION")
}
public seek(pos: number) {
return this.sendCommandAsync("SEEK", pos.toString())
}
private interval: ReturnType<typeof setInterval> | undefined
private clearInterval() {
if (this.interval) {
clearInterval(this.interval)
this.interval = undefined
}
}
private initializePositionListener() {
this.interval = setInterval(async () => {
const pos = await this.getPosition()
this.emit('timeUpdate', pos)
}, 1000)
}
}