-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathSequencer.js
265 lines (228 loc) · 7.03 KB
/
Sequencer.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
import promisify from "./promisify-xhr";
import {CATALOG_PREFIX} from "./config";
import shuffle from 'lodash/shuffle';
import EventEmitter from 'events';
import autoBind from 'auto-bind';
import { pathJoin } from './util';
export const REPEAT_OFF = 0;
export const REPEAT_ALL = 1;
export const REPEAT_ONE = 2;
export const NUM_REPEAT_MODES = 3;
export const REPEAT_LABELS = ['Off', 'All', 'One'];
export const SHUFFLE_OFF = 0;
export const SHUFFLE_ON = 1;
export const NUM_SHUFFLE_MODES = 2;
export const SHUFFLE_LABELS = ['Off', 'On'];
export default class Sequencer extends EventEmitter {
constructor(players, localFilesManager) {
super();
autoBind(this);
this.player = null;
this.players = players;
this.localFilesManager = localFilesManager;
// this.onSequencerStateUpdate = onSequencerStateUpdate;
// this.onPlayerError = onError;
this.currIdx = 0;
this.context = null;
this.currUrl = null;
this.shuffle = SHUFFLE_OFF;
this.shuffleOrder = [];
this.songRequest = null;
this.repeat = REPEAT_OFF;
this.players.forEach(player => {
player.on('playerStateUpdate', this.handlePlayerStateUpdate);
player.on('playerError', this.handlePlayerError);
});
}
handlePlayerError(e) {
this.emit('playerError', e);
if (this.context) {
this.nextSong();
} else {
this.emit('sequencerStateUpdate', { isEjected: true });
}
}
handlePlayerStateUpdate(playerState) {
const { isStopped } = playerState;
console.debug('Sequencer.handlePlayerStateUpdate(isStopped=%s)', isStopped);
if (isStopped) {
this.currUrl = null;
if (this.context) {
this.nextSong();
}
} else {
this.emit('sequencerStateUpdate', {
url: this.currUrl,
hasPlayer: true,
// TODO: combine isEjected and hasPlayer
isEjected: false,
...playerState,
});
}
}
playContext(context, index = 0, subtune = 0) {
this.currIdx = index;
this.context = context;
if (this.shuffle === SHUFFLE_ON) {
this.setShuffle(this.shuffle);
}
this.playCurrentSong(subtune);
}
playCurrentSong(subtune = 0) {
let idx = this.currIdx;
if (this.shuffle === SHUFFLE_ON) {
idx = this.shuffleOrder[idx];
console.log('Shuffle (%s): %s', this.currIdx, idx);
}
this.playSong(this.context[idx], subtune);
}
playSonglist(urls) {
this.playContext(urls, 0);
}
toggleShuffle() {
this.setShuffle(!this.shuffle);
}
setShuffle(shuff) {
this.shuffle = shuff;
if (this.shuffle === SHUFFLE_ON && this.context) {
// Generate a new shuffle order.
// Insert current play index at the beginning.
this.shuffleOrder = [this.currIdx, ...shuffle(this.context.map((_, i) => i).filter(i => i !== this.currIdx))];
this.currIdx = 0;
} else if (this.shuffleOrder) {
// Restore linear play sequence at current shuffle position.
if (this.shuffleOrder[this.currIdx] !== null) {
this.currIdx = this.shuffleOrder[this.currIdx];
}
}
}
setRepeat(repeat) {
this.repeat = repeat;
}
advanceSong(direction) {
if (this.context == null) return;
if (this.repeat !== REPEAT_ONE) {
this.currIdx += direction;
}
if (this.currIdx < 0 || this.currIdx >= this.context.length) {
if (this.repeat === REPEAT_ALL) {
this.currIdx = (this.currIdx + this.context.length) % this.context.length;
this.playCurrentSong();
} else {
console.debug('Sequencer.advanceSong(direction=%s) %s passed end of context length %s',
direction, this.currIdx, this.context.length);
this.currIdx = 0;
this.context = null;
this.player.stop();
this.player = null;
this.emit('sequencerStateUpdate', { isEjected: true });
}
} else {
this.playCurrentSong();
}
}
nextSong() {
this.advanceSong(1);
}
prevSong() {
this.advanceSong(-1);
}
playSubtune(subtune) {
this.player.playSubtune(subtune);
}
prevSubtune() {
const subtune = this.player.getSubtune() - 1;
if (subtune < 0) return;
this.playSubtune(subtune);
}
nextSubtune() {
const subtune = this.player.getSubtune() + 1;
if (subtune >= this.player.getNumSubtunes()) return;
this.playSubtune(subtune);
}
getPlayer() {
return this.player;
}
getCurrContext() {
return this.context;
}
getCurrIdx() {
return this.shuffle ? this.shuffleOrder[this.currIdx] : this.currIdx;
}
getCurrUrl() {
return this.currUrl;
}
getSubtune() {
return this.player.getSubtune();
}
playSong(url, subtune = 0) {
if (this.player !== null) {
this.player.suspend();
}
// Find a player that can play this filetype
const ext = url.split('.').pop().toLowerCase();
for (let i = 0; i < this.players.length; i++) {
if (this.players[i].canPlay(ext)) {
this.player = this.players[i];
break;
}
}
if (this.player === null) {
this.emit('playerError', `The file format ".${ext}" was not recognized.`);
return;
}
if (url.startsWith('local/')) {
const buffer = this.localFilesManager.read(url);
this.currUrl = null;
this.playSongBuffer(url, buffer, subtune);
} else {
// Normalize url - paths are assumed to live under CATALOG_PREFIX
url = url.startsWith('http') ? url : pathJoin(CATALOG_PREFIX, url);
// Fetch the song file (cancelable request)
// Cancel any outstanding request so that playback doesn't happen out of order
if (this.songRequest) this.songRequest.abort();
this.songRequest = promisify(new XMLHttpRequest());
this.songRequest.responseType = 'arraybuffer';
this.songRequest.open('GET', url);
this.songRequest.send()
.then(xhr => xhr.response)
.then(buffer => {
this.currUrl = url;
const filepath = url.replace(CATALOG_PREFIX, '');
this.playSongBuffer(filepath, buffer, subtune)
})
.catch(e => {
this.handlePlayerError(e.message || `HTTP ${e.status} ${e.statusText} ${url}`);
});
}
}
playSongFile(filepath, songData) {
if (this.player !== null) {
this.player.suspend();
}
const ext = filepath.split('.').pop().toLowerCase();
// Find a player that can play this filetype
const player = this.players.find(player => player.canPlay(ext));
if (player == null) {
this.emit('playerError', `The file format ".${ext}" was not recognized.`);
return;
} else {
this.player = player;
}
this.context = [];
this.currUrl = null;
this.playSongBuffer(filepath, songData);
}
async playSongBuffer(filepath, buffer, subtune = 0) {
let uint8Array;
uint8Array = new Uint8Array(buffer);
this.player.setTempo(1);
try {
await this.player.loadData(uint8Array, filepath, subtune);
} catch (e) {
this.handlePlayerError(`Unable to play ${filepath} (${e.message}).`);
}
const numVoices = this.player.getNumVoices();
this.player.setVoiceMask([...Array(numVoices)].fill(true));
}
}