-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaudio.js
99 lines (83 loc) · 2.95 KB
/
audio.js
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
94
95
96
97
98
99
const path = require('path');
var player = require('play-sound')(opts = { player: 'omxplayer' })
const EVENTS = require('./events');
module.exports = class Audio {
constructor(opts) {
this.logger = opts.logger
this.EE = opts.EE
this.queue = []
this.playing = false
// don't turn on by default, wait until lid is open
this.enabled = false
// listen for open event and then turn on audio
this.EE.on(EVENTS.BOMB_OPENED, () => {
this.logger.log('audio: trunk opened. enabled audio.')
this.enabled = true
});
// when the bomb is reset, turn the audio back off
this.EE.on(EVENTS.BOMB_RESET, () => {
this.logger.log('audio: trunk reset. disabling audio.')
this.enabled = false
});
}
play(files, cb, delayInMs) {
if (!this.enabled) {
this.logger.log('audio: trunk closed. ignoring request to play file.')
if (cb) cb()
return;
}
// if more than one file to play, queue it up
if (Array.isArray(files)) {
for (let file of files) {
this.queue.push(file)
}
} else {
this.queue.push(files)
}
if (!this.playing) {
delayInMs = delayInMs ? delayInMs : 0
setTimeout(()=>{
this.dequeueAndPlay(cb)
}, delayInMs)
} else {
this.logger.log('audio: audio already playing, so added to queue.')
if (cb) cb()
}
}
dequeueAndPlay(cb) {
let fileName = this.queue.shift()
let fullFile = path.join(__dirname, 'audio', fileName);
this.logger.log('audio: playing \'' + fileName + '\'...')
this.playing = true
player.play(fullFile, (err) => {
if (err) {
this.logger.logger.error('audio: Exception: ' + err)
} else {
this.logger.log('audio: played.')
}
this.playing = false
if (this.queue.length > 0) {
this.dequeueAndPlay(cb)
} else if (cb) {
cb()
}
})
}
playTimed(fileName, delay) {
if (!this.enabled) {
this.logger.log('audio: trunk closed. ignoring request to play file timed.')
return;
}
setTimeout(() => {
let fullFile = path.join(__dirname, 'audio', fileName);
this.logger.log('audio: playing timed \'' + fileName + '\'...')
player.play(fullFile, (err) => {
if (err) {
this.logger.logger.error('audio: Timed Exception: ' + err)
} else {
this.logger.log('audio: timed played (\'' + fileName + '\').')
}
})
}, delay);
}
}