-
Notifications
You must be signed in to change notification settings - Fork 0
/
player.js
426 lines (374 loc) · 13.6 KB
/
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
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
class CodeRadio {
constructor() {
/***
* General configuration options
*/
this.config = {
baseColour: "rgb(10, 10, 35)",
translucent: "rgba(10, 10, 35, 0.6)",
multiplier: 0.7529,
metadataTimer: 2000
};
/***
* The equalizer data is held as a seperate data set
* to allow for easy implementation of visualizers.
* With the ultimate goal of this allowing plug and
* play visualizers.
*/
this.eq = {};
/***
* Potentially removing the visualizer from this class
* to build it as a stand alone element that can be
* replaced by community submissions
*/
this.visualizer = {};
// Some basic configuration for nicer audio transitions
// (Used in earlier projects and just maintained)
this.audioConfig = {
targetVolume: 0,
maxVolume: 0.5,
volumeSteps: 0.1,
volumeTransitionSpeed: 100
};
/***
* This is where all the audio is pumped through. Due
* to it being a single audio element, there should be
* no memory leaks of extra floating audio elements.
*/
this._url = "";
this._player = new Audio();
this._player.volume = this.audioConfig.maxVolume;
this._player.crossOrigin = "anonymous";
this._streams = [];
// Note: the crossOrigin is needed to fix a CORS JavaScript requirement
/***
* There are a few *private* variables used
*/
this._currentSong = {};
this._songStartedAt = 0;
this._songDuration = 0;
this._progressInterval = false;
this.getNowPlaying();
this.meta = {
container: document.getElementById("nowPlaying"),
picture: document.querySelector('[data-meta="picture"]'),
title: document.querySelector('[data-meta="title"]'),
artist: document.querySelector('[data-meta="artist"]'),
album: document.querySelector('[data-meta="album"]'),
duration: document.querySelector('[data-meta="duration"]'),
listeners: document.querySelector('[data-meta="listeners"]'),
dropdown: document.querySelector('[data-meta="dropdown"]')
};
this.setupEventListeners();
}
/***
* If we ever change the URL, we need to update the player
* and begin playing it again. This can happen if the server
* resets the URL.
*/
set url(url = false) {
if (url && this._url === "") {
this._url = url;
this._player.src = url;
this._player.play();
}
}
get url() {
return this._url;
}
/***
* The song data is always checked with the ID of the current
* one. If it is not the same, the data is then updated and
* the metadata is updated.
*/
set currentSong(songData = {}) {
this._currentSong = songData;
this.renderMetadata();
}
get currentSong() {
return this._currentSong;
}
/***
* In order to get the constant durations, we simply take the
* duration for the max of the meter and set the played at to 0
*/
set played_at(t = 0) {
this._songStartedAt = t * 1000; // Time comes in a seconds so we multiply by 1000 to set millis
this.meta.duration.value = 0;
}
get played_at() {
return this._songStartedAt;
}
set duration(d = 0) {
this._songDuration = d;
this.meta.duration.max = this._songDuration;
}
get duration() {
return this._songDuration;
}
getNowPlaying() {
// To prevent browser based caching, we add the date to the request, it won't impact the response
fetch(`app/api/nowplaying?t=${new Date().valueOf()}`)
.then(req => req.json())
.then(np => {
np = np[0]; // There is only ever 1 song "Now Playing" so let's simplify the response
// We look through the available mounts to find the default mount (or just the listen_url)
if (this.url === "") {
this.url = np.station.mounts.find(mount => !!mount.is_default).url;
this._streams = np.station.mounts.concat(np.station.remotes);
this.renderStreams();
console.log(this._streams);
}
//this.streams = np.station.mounts.concat(np.station.remotes);
// We only need to update th metadata if the song has been changed
if (
!this.currentSong.id ||
np.now_playing.song.id !== this.currentSong.id
) {
this.currentSong = np.now_playing.song;
this.played_at = np.now_playing.played_at;
this.duration = np.now_playing.duration;
this.meta.listeners.textContent = `coders listening now:${
np.listeners.current
}`;
if (!this._progressInterval) {
this._progressInterval = setInterval(
() => this.updateProgress(),
100
);
}
}
// Since the server doesn't have a socket connection (yet), we need to long poll it for the current song
setTimeout(() => this.getNowPlaying(), this.config.metadataTimer);
})
.catch(err => {
console.error(err);
setTimeout(() => this.getNowPlaying(), this.config.metadataTimer * 3);
});
}
/***
* Yay, let's get some keyboard shortcuts in this tool
*/
setupEventListeners() {
document.addEventListener("keydown", evt => this.keyboardControl(evt));
// listen for changes in the dropdown
this.meta.dropdown.addEventListener("change", evt =>
this.handleDropdownChange(evt)
);
// In order to get around some mobile browser limitations, we can only generate a lot
// of the audio context stuff AFTER the audio has been triggered. We can't see it until
// then anyway so it makes no difference to desktop.
this._player.addEventListener("play", () => {
if (!this.eq.context) {
this.initiateEQ();
this.createVisualizer();
}
});
}
//handle drop down changes
//note: pause before play because play() requires pause :)
handleDropdownChange(evt = {}) {
let target = evt.target.value;
let value = this._streams.forEach(stream => {
if (stream.name === target) {
this._url = stream.url;
this.pause();
this.play();
return;
}
});
evt.target.value;
}
keyboardControl(evt = {}) {
// Quick note: if you're wanting to do similar in your projects, keyCode use to be the
// standard however it is being depricated for the key attribute
switch (evt.key) {
case " ":
case "k":
this.togglePlay();
break;
case "ArrowUp":
this.setTargetVolume(
Math.min(this.audioConfig.maxVolume + this.audioConfig.volumeSteps, 1)
);
break;
case "ArrowDown":
this.setTargetVolume(
Math.max(this.audioConfig.maxVolume - this.audioConfig.volumeSteps, 0)
);
break;
}
}
initiateEQ() {
// Create a new Audio Context element to read the samples from
this.eq.context = new AudioContext();
// Apply the audio element as the source where to pull all the data from
this.eq.src = this.eq.context.createMediaElementSource(this._player);
// Use some amazing trickery that allows javascript to analyse the current state
this.eq.analyser = this.eq.context.createAnalyser();
this.eq.src.connect(this.eq.analyser);
this.eq.analyser.connect(this.eq.context.destination);
this.eq.analyser.fftSize = 256;
// Create a buffer array for the number of frequencies available (minus the high pitch useless ones that never really do anything anyway)
this.eq.bands = new Uint8Array(this.eq.analyser.frequencyBinCount - 32);
this.updateEQBands();
}
/***
* The equalizer bands available need to be updated
* constantly in order to ensure that the value for any
* visualizer is up to date.
*/
updateEQBands() {
// Populate the buffer with the audio source’s current data
this.eq.analyser.getByteFrequencyData(this.eq.bands);
// Can’t stop, won’t stop
requestAnimationFrame(() => this.updateEQBands());
}
/***
* When starting the page, the visualizer dom is needed to be
* created.
*/
createVisualizer() {
let container = document.createElement("canvas");
document.getElementById("visualizer").appendChild(container);
container.width = container.parentNode.offsetWidth;
container.height = container.parentNode.offsetHeight;
this.visualizer = {
ctx: container.getContext("2d"),
height: container.height,
width: container.width,
barWidth: container.width / this.eq.bands.length
};
this.drawVisualizer();
}
/***
* As a base visualizer, the equalizer bands are drawn using
* canvas in the window directly above the song into.
*/
drawVisualizer() {
if (this.eq.bands.reduce((a, b) => a + b, 0) !== 0)
requestAnimationFrame(() => this.drawVisualizer());
// Because timeupdate events are not triggered at browser speed, we use requestanimationframe for higher framerates
else setTimeout(() => this.drawVisualizer(), 250); // If there is no music or audio in the song, then reduce the FPS
let y,
x = 0; // Intial bar x coordinate
this.visualizer.ctx.clearRect(
0,
0,
this.visualizer.width,
this.visualizer.height
); // Clear the complete canvas
this.visualizer.ctx.fillStyle = this.config.translucent; // Set the primary colour of the brand (probably moving to a higher object level variable soon)
this.visualizer.ctx.beginPath(); // Start creating a canvas polygon
this.visualizer.ctx.moveTo(x, 0); // Start at the bottom left
this.eq.bands.forEach(band => {
y = this.config.multiplier * band; // Get the overall hight associated to the current band and convert that into a Y position on the canvas
this.visualizer.ctx.lineTo(x, y); // Draw a line from the current position to the wherever the Y position is
this.visualizer.ctx.lineTo(x + this.visualizer.barWidth, y); // Continue that line to meet the width of the bars (canvas width ÷ bar count)
x += this.visualizer.barWidth; // Add pixels to the x for the next bar
});
this.visualizer.ctx.lineTo(x, 0); // Bring the line back down to the bottom of the canvas
this.visualizer.ctx.fill(); // Fill it
}
play() {
if (this._player.paused) {
this._player.volume = 0;
this._player.play();
this.fadeUp();
return this;
}
}
pause() {
this._player.pause();
return this;
}
/***
* Very basic method that acts like the play/pause button
* of a standard player. It loads in a new song if there
* isn’t already one loaded.
*/
togglePlay() {
// If there already is a source, confirm it’s playing or not
if (!!this._player.src) {
// If the player is paused, set the volume to 0 and fade up
if (this._player.paused) {
this._player.volume = 0;
this._player.play();
this.fadeUp();
// if it is already playing, fade the music out (resulting in a pause)
} else this.fade();
}
return this;
}
setTargetVolume(v) {
this.audioConfig.maxVolume = parseFloat(
Math.max(0, Math.min(1, v).toFixed(1))
);
this._player.volume = this.audioConfig.maxVolume;
}
// Simple fade command to initiate the playing and pausing in a more fluid method
fade(direction = "down") {
this.audioConfig.targetVolume =
direction.toLowerCase() === "up" ? this.audioConfig.maxVolume : 0;
this.updateVolume();
return this;
}
// Helper methods to simplify things
fadeDown() {
return this.fade("down");
}
fadeUp() {
return this.fade("up");
}
// In order to have nice fading, this method adjusts the volume dynamically over time.
updateVolume() {
// In order to fix floating math issues, we set the toFixed in order to avoid 0.999999999999 increments
let currentVolume = parseFloat(this._player.volume.toFixed(1));
// If the volume is correctly set to the target, no need to change it
if (currentVolume === this.audioConfig.targetVolume) {
// If the audio is set to 0 and it’s been met, pause the audio
if (this.audioConfig.targetVolume === 0) this._player.pause();
// Unmet audio volume settings require it to be changed
} else {
// We capture the value of the next increment by either the configuration or the difference between the current and target if it's smaller than the increment
let volumeNextIncrement = Math.min(
this.audioConfig.volumeSteps,
Math.abs(this.audioConfig.targetVolume - this._player.volume)
);
// Adjust the audio based on if the target is higher or lower than the current
this._player.volume +=
this.audioConfig.targetVolume > this._player.volume
? volumeNextIncrement
: -volumeNextIncrement;
// The speed at which the audio lowers is also controlled.
setTimeout(
() => this.updateVolume(),
this.audioConfig.volumeTransitionSpeed
);
}
}
renderMetadata() {
if (!!this._currentSong.art) {
this.meta.picture.style.backgroundImage = `url(${this._currentSong.art})`;
this.meta.container.classList.add("thumb");
} else {
this.meta.container.classList.remove("thumb");
this.meta.picture.style.backgroundImage = "";
}
this.meta.title.textContent = this._currentSong.title;
this.meta.artist.textContent = this._currentSong.artist;
this.meta.album.textContent = this._currentSong.album;
}
renderStreams() {
this._streams.forEach(stream => {
let option = document.createElement("option");
option.value = stream.name;
option.textContent = stream.name;
this.meta.dropdown.appendChild(option);
});
}
updateProgress() {
this.meta.duration.value =
(new Date().valueOf() - this._songStartedAt) / 1000;
}
}