-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaudio-player.js
54 lines (46 loc) · 1.13 KB
/
audio-player.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
// NOTE: We are expecting you to *create* an AudioPlayer, but we are *not*
// expecting you to modify the contents of this file.
class AudioPlayer {
constructor() {
this._onKickCallback = this._onKickCallback.bind(this);
this.lastKickTime = -1;
this.dancer = new Dancer();
this.kick = this.dancer.createKick({
onKick: this._onKickCallback
});
this.kick.on();
}
setSong(songUrl) {
let audio = new Audio();
audio.crossOrigin = 'anonymous';
audio.loop = 'true';
audio.src = songUrl;
this.dancer.pause();
this.dancer.load(audio);
}
play() {
this.dancer.play();
const nowTime = Date.now();
if (this.lastKickTime === -1) {
this.lastKickTime = nowTime;
}
}
pause() {
this.dancer.pause();
}
setKickCallback(kickCallback) {
this.kickCallback = kickCallback;
}
_onKickCallback() {
if (!this.kickCallback) {
return;
}
const KICK_THRESHOLD = 0.2;
const nowTime = Date.now();
const diff = (nowTime - this.lastKickTime) / 1000;
if (diff > KICK_THRESHOLD) {
this.lastKickTime = nowTime;
this.kickCallback();
}
}
}