-
Notifications
You must be signed in to change notification settings - Fork 6
/
main.ts
905 lines (798 loc) · 26.2 KB
/
main.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
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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
import {
Plugin,
debounce,
setIcon,
requestUrl,
Notice,
WorkspaceLeaf,
} from "obsidian";
import fs from "fs";
import path from "path";
import MusicMetadata from "music-metadata";
import Observable from "src/Utils/Observable";
import { ReactView, SOUNDSCAPES_REACT_VIEW } from "./Views/ReactView";
import getAllMusicFiles from "src/Utils/getAllMusicFiles";
import { LocalPlayerState, Player } from "src/Types/Interfaces";
import { PLAYER_STATE, SOUNDSCAPE_TYPE } from "src/Types/Enums";
import SOUNDSCAPES from "src/Soundscapes";
import {
DEFAULT_SETTINGS,
SoundscapesPluginSettings,
SoundscapesSettingsTab,
} from "src/Settings/Settings";
import createShuffleQueue from "src/Utils/createShuffleQueue";
/**
* This allows a "live-reload" of Obsidian when developing the plugin.
* Any changes to the code will force reload Obsidian.
*/
if (process.env.NODE_ENV === "development") {
new EventSource("http://127.0.0.1:8000/esbuild").addEventListener(
"change",
() => location.reload()
);
}
export default class SoundscapesPlugin extends Plugin {
settings: SoundscapesPluginSettings;
settingsObservable: Observable;
localPlayerStateObservable: Observable;
player: Player;
localPlayer: HTMLAudioElement;
statusBarItem: HTMLElement;
playButton: HTMLButtonElement;
pauseButton: HTMLButtonElement;
nextButton: HTMLButtonElement;
previousButton: HTMLButtonElement;
changeSoundscapeSelect: HTMLSelectElement;
nowPlayingRoot: HTMLDivElement;
nowPlaying: HTMLDivElement;
volumeMutedIcon: HTMLDivElement;
volumeLowIcon: HTMLDivElement;
volumeHighIcon: HTMLDivElement;
volumeSlider: HTMLInputElement;
ribbonButton: HTMLElement;
debouncedSaveSettings: Function;
soundscapeType: SOUNDSCAPE_TYPE;
currentTrackIndex: number = 0;
reindexTimer: NodeJS.Timeout | null = null;
shuffleQueue: number[] = [];
shuffleQueueSpot: number = 0;
async onload() {
await this.loadSettings();
this.currentTrackIndex = this.settings.currentTrackIndex; // Persist the current track when closing and opening
this.settingsObservable = new Observable(this.settings);
this.localPlayerStateObservable = new Observable({});
this.debouncedSaveSettings = debounce(this.saveSettings, 500, true);
this.versionCheck();
this.statusBarItem = this.addStatusBarItem();
this.statusBarItem.addClass("soundscapesroot");
this.createPlayer();
this.registerView(
SOUNDSCAPES_REACT_VIEW,
(leaf) =>
new ReactView(
this,
this.settingsObservable,
this.localPlayerStateObservable,
leaf
)
);
this.ribbonButton = this.addRibbonIcon(
"music",
"Soundscapes: My Music",
() => {
this.OpenMyMusicView();
}
);
this.ribbonButton.hide();
// This adds a settings tab so the user can configure various aspects of the plugin
this.addSettingTab(new SoundscapesSettingsTab(this.app, this));
if (this.settings.soundscape === SOUNDSCAPE_TYPE.MY_MUSIC) {
this.ribbonButton.show();
// Delay this so startup isn't impacted
setTimeout(() => {
this.indexMusicLibrary();
}, 1000);
}
}
onunload() {
// Clear any timers if they exist
if (this.reindexTimer) {
clearTimeout(this.reindexTimer);
}
}
/**
* Because we only have the id of the current soundscape, we need a helper function to get the soundscape itself when it's a custom one
* @returns
*/
getCurrentCustomSoundscape() {
return this.settings.customSoundscapes.find(
(soundscape) =>
soundscape.id ===
this.settings.soundscape.split(`${SOUNDSCAPE_TYPE.CUSTOM}_`)[1]
);
}
/******************************************************************************************************************/
//#region Startup
/******************************************************************************************************************/
/**
* Check the local plugin version against github. If there is a new version, notify the user.
*/
async versionCheck() {
const localVersion = process.env.PLUGIN_VERSION;
const stableVersion = await requestUrl(
"https://raw.githubusercontent.com/andrewmcgivery/obsidian-soundscapes/main/package.json"
).then(async (res) => {
if (res.status === 200) {
const response = await res.json;
return response.version;
}
});
const betaVersion = await requestUrl(
"https://raw.githubusercontent.com/andrewmcgivery/obsidian-soundscapes/beta/package.json"
).then(async (res) => {
if (res.status === 200) {
const response = await res.json;
return response.version;
}
});
if (localVersion?.indexOf("beta") !== -1) {
if (localVersion !== betaVersion) {
new Notice(
"There is a beta update available for the Soundscapes plugin. Please update to to the latest version to get the latest features!",
0
);
}
} else if (localVersion !== stableVersion) {
new Notice(
"There is an update available for the Soundscapes plugin. Please update to to the latest version to get the latest features!",
0
);
}
}
/**
* Given a file path in settings, get all the music files in that folder.
* Convert those music files to a index of their music metadata.
* Finally, reschedule the next reindex based on settings.
*/
async indexMusicLibrary() {
console.time("MusicIndex");
const filePath = this.settings.myMusicFolderPath;
// Clear any timers if they exist
if (this.reindexTimer) {
clearTimeout(this.reindexTimer);
}
if (filePath.trim() === "") {
new Notice(
"Please set music file path in settings to use My Music feature of Soundscapes.",
0
);
return;
}
new Notice("Soundscapes: Indexing local music files...");
const musicFilePaths = getAllMusicFiles(filePath);
const musicPromises = musicFilePaths.map(async (filePath) => {
const metadata = await MusicMetadata.parseFile(filePath, {
skipCovers: true,
});
return {
fileName: path.basename(filePath),
fullPath: filePath,
title:
metadata.common.title ||
path.basename(filePath).replace(/\.(mp3)$/gi, ""),
artist: metadata.common.artist,
album: metadata.common.album,
duration: metadata.format.duration,
};
});
const songs = await Promise.all(musicPromises);
console.timeEnd("MusicIndex");
this.settings.myMusicIndex = songs;
new Notice(
`Soundscapes: Indexing complete. ${songs.length} songs were indexed.`
);
if (songs.length === 0) {
new Notice(
`Warning: Soundscapes found no songs at the configured file path.`
);
}
this.saveSettings();
// Reschedule index based on settings
if (this.settings.reindexFrequency !== "never") {
this.reindexTimer = setTimeout(
() => this.indexMusicLibrary(),
60000 * parseInt(this.settings.reindexFrequency)
);
}
}
/******************************************************************************************************************/
//#endregion Startup
/******************************************************************************************************************/
/******************************************************************************************************************/
//#region Create UI Elements
/******************************************************************************************************************/
/**
* Opens react view of MyMusic
*/
async OpenMyMusicView() {
const { workspace } = this.app;
let leaf: WorkspaceLeaf | null = null;
const leaves = workspace.getLeavesOfType(SOUNDSCAPES_REACT_VIEW);
if (leaves.length > 0) {
// A leaf with our view already exists, use that
leaf = leaves[0];
} else {
// Our view could not be found in the workspace, create a new leaf for it
leaf = workspace.getLeaf(true);
await leaf.setViewState({
type: SOUNDSCAPES_REACT_VIEW,
active: true,
});
}
// "Reveal" the leaf in case it is in a collapsed sidebar
workspace.revealLeaf(leaf);
}
/**
* Create the Youtube player
*/
createPlayer() {
// Load in youtube iframe api script
const ytScript = this.statusBarItem.createEl("script", {
attr: {
src: "https://www.youtube.com/iframe_api",
},
});
ytScript.addEventListener("error", () => {
new Notice(
"Soundscapes was unable to load the Youtube player. This could be because you are offline or have youtube blocked. You may still use My Music mode."
);
this.onPlayerReady();
});
// Create div to insert the video into
this.statusBarItem.createEl("div", {
attr: { id: "player" },
cls: "soundscapesroot-player",
});
// Create local media player and listen to events
this.localPlayer = new Audio();
this.localPlayer.volume = this.settings.volume / 100;
this.localPlayer.addEventListener("play", () => {
this.onStateChange({ data: PLAYER_STATE.PLAYING });
});
this.localPlayer.addEventListener("pause", () => {
this.onStateChange({ data: PLAYER_STATE.PAUSED });
});
this.localPlayer.addEventListener("ended", () => {
this.onStateChange({ data: PLAYER_STATE.ENDED });
});
this.localPlayer.addEventListener("timeupdate", () => {
this.updateLocalPlayerState({
currentTime: this.localPlayer.currentTime,
});
});
// Once the API is ready, create a player
// @ts-ignore
window.onYouTubeIframeAPIReady = () => {
// @ts-ignore
this.player = new YT.Player("player", {
height: "100",
width: "200",
playerVars: {
playsinline: 1,
fs: 0,
disablekb: 1,
controls: 0,
},
events: {
onReady: this.onPlayerReady.bind(this),
onStateChange: (e: any) => {
// This is to suppress the player from sending events when it's not the active player
if (
this.settings.soundscape !==
SOUNDSCAPE_TYPE.MY_MUSIC
) {
this.onStateChange.bind(this)(e);
}
},
},
});
};
}
/**
* Create all the UI elements
*/
createControls() {
// Previous Button
this.previousButton = this.statusBarItem.createEl("button", {
cls: "soundscapesroot-previousbutton",
});
setIcon(this.previousButton, "skip-back");
this.previousButton.onclick = () => this.previous();
// Play Button
this.playButton = this.statusBarItem.createEl("button", {});
setIcon(this.playButton, "play");
this.playButton.onclick = () => this.play();
// Pause Button
this.pauseButton = this.statusBarItem.createEl("button", {});
setIcon(this.pauseButton, "pause");
this.pauseButton.onclick = () => this.pause();
// Next Button
this.nextButton = this.statusBarItem.createEl("button", {
cls: "soundscapesroot-nextbutton",
});
setIcon(this.nextButton, "skip-forward");
this.nextButton.onclick = () => this.next();
// Change Soundscape Button
const changeSoundscapeButton = this.statusBarItem.createEl("button", {
cls: "soundscapesroot-changesoundscapebutton",
});
setIcon(changeSoundscapeButton, "list-music");
this.changeSoundscapeSelect = changeSoundscapeButton.createEl(
"select",
{
cls: "soundscapesroot-changesoundscapeselect",
attr: {
id: "soundscapesroot-changesoundscapeselect",
},
}
);
this.populateChangeSoundscapeButton();
// Now Playing
this.nowPlayingRoot = this.statusBarItem.createEl("div", {
cls: "soundscapesroot-nowplaying",
});
this.nowPlaying = this.nowPlayingRoot.createEl("div", {
cls: "soundscapesroot-nowplaying-text",
});
this.toggleNowPlayingScroll();
// Volume control
const volumeIcons = this.statusBarItem.createEl("div", {
cls: "soundscapesroot-volumeIcons",
});
this.volumeMutedIcon = volumeIcons.createEl("div", {
cls: "soundscapesroot-volumeIcons-iconmuted",
});
setIcon(this.volumeMutedIcon, "volume-x");
this.volumeLowIcon = volumeIcons.createEl("div", {
cls: "soundscapesroot-volumeIcons-iconlow",
});
setIcon(this.volumeLowIcon, "volume-1");
this.volumeHighIcon = volumeIcons.createEl("div", {
cls: "soundscapesroot-volumeIcons-iconhigh",
});
setIcon(this.volumeHighIcon, "volume-2");
this.volumeSlider = this.statusBarItem.createEl("input", {
attr: {
type: "range",
min: 0,
max: 100,
value: this.settings.volume,
},
});
// Create a virtual event object
this.onVolumeChange({ target: { value: this.settings.volume } });
this.volumeSlider.addEventListener(
"input",
this.onVolumeChange.bind(this)
);
}
/**
* Populates the dropdown on the miniplayer with all available soundscapes
*/
populateChangeSoundscapeButton() {
this.changeSoundscapeSelect.replaceChildren();
Object.values(SOUNDSCAPES).forEach((soundscape) => {
this.changeSoundscapeSelect.createEl("option", {
text: soundscape.name,
value: soundscape.id,
});
});
this.settings.customSoundscapes.forEach((customSoundscape) => {
if (customSoundscape.tracks.length > 0) {
this.changeSoundscapeSelect.createEl("option", {
text: customSoundscape.name,
value: `${SOUNDSCAPE_TYPE.CUSTOM}_${customSoundscape.id}`,
});
}
});
this.changeSoundscapeSelect.createEl("option", {
text: "My Music",
value: SOUNDSCAPE_TYPE.MY_MUSIC,
});
this.changeSoundscapeSelect.value = this.settings.soundscape;
this.changeSoundscapeSelect.addEventListener(
"change",
(event: Event) => {
this.changeSoundscape(
(event?.target as HTMLSelectElement).value
);
}
);
}
/******************************************************************************************************************/
//#endregion Create UI Elements
/******************************************************************************************************************/
/******************************************************************************************************************/
//#region Control Player
/******************************************************************************************************************/
/**
* Plays the current track. When it's a live video, attempt to jump to the "live" portion.
*/
play() {
if (
this.soundscapeType === SOUNDSCAPE_TYPE.STANDARD &&
SOUNDSCAPES[this.settings.soundscape].isLiveVideo
) {
this.player?.seekTo(this.player.getDuration());
}
if (this.soundscapeType === SOUNDSCAPE_TYPE.MY_MUSIC) {
// If we don't currently have an audio source because we recently changed folders but now we do have an index, play the first song
if (
this.localPlayer.src === location.href &&
this.settings.myMusicIndex.length > 0
) {
this.currentTrackIndex = 0;
this.onSoundscapeChange(true);
} else {
this.localPlayer.play();
}
} else {
this.player?.playVideo();
}
}
/**
* Pause the current track.
*/
pause() {
if (this.soundscapeType === SOUNDSCAPE_TYPE.MY_MUSIC) {
this.localPlayer.pause();
} else {
this.player?.pauseVideo();
}
}
/**
* Skip to the previous track.
*/
previous() {
if (this.soundscapeType === SOUNDSCAPE_TYPE.CUSTOM) {
const customSoundscape = this.getCurrentCustomSoundscape();
if (this.currentTrackIndex === 0) {
this.currentTrackIndex =
(customSoundscape?.tracks.length || 1) - 1;
} else {
this.currentTrackIndex--;
}
} else if (this.soundscapeType === SOUNDSCAPE_TYPE.MY_MUSIC) {
// Are we in shuffle mode?
if (this.settings.myMusicShuffle) {
// If Shuffle queue is empty, let's populate it
if (this.shuffleQueue.length === 0) {
this.shuffleQueue = createShuffleQueue(
this.settings.myMusicIndex
);
this.shuffleQueueSpot = 0;
}
if (this.shuffleQueueSpot === 0) {
// If we are at the beginning, wrap around to the end!
this.currentTrackIndex =
this.shuffleQueue[this.shuffleQueue.length - 1];
} else {
// Otherwise, go to the previous song in the shuffle queue
this.shuffleQueueSpot--;
this.currentTrackIndex =
this.shuffleQueue[this.shuffleQueueSpot];
}
} else {
// Not in shuffle mode, go to next song
if (this.currentTrackIndex === 0) {
this.currentTrackIndex =
this.settings.myMusicIndex.length - 1;
} else {
this.currentTrackIndex--;
}
}
}
this.onSoundscapeChange();
}
/**
* Skip to the next track.
*/
next() {
if (this.soundscapeType === SOUNDSCAPE_TYPE.CUSTOM) {
const customSoundscape = this.getCurrentCustomSoundscape();
if (customSoundscape?.tracks[this.currentTrackIndex + 1]) {
this.currentTrackIndex++;
} else {
this.currentTrackIndex = 0;
}
} else if (this.soundscapeType === SOUNDSCAPE_TYPE.MY_MUSIC) {
// Are we in shuffle mode?
if (this.settings.myMusicShuffle) {
// If Shuffle queue is empty, let's populate it
if (this.shuffleQueue.length === 0) {
this.shuffleQueue = createShuffleQueue(
this.settings.myMusicIndex
);
this.shuffleQueueSpot = 0;
}
if (this.shuffleQueueSpot === this.shuffleQueue.length - 1) {
// If we get to the end of all possible songs to shuffle, go back to the start and reset the shuffle queue
this.currentTrackIndex = this.shuffleQueue[0];
this.shuffleQueue = [];
this.shuffleQueueSpot = 0;
} else {
// Otherwise, go to the next song in the shuffle queue
this.shuffleQueueSpot++;
this.currentTrackIndex =
this.shuffleQueue[this.shuffleQueueSpot];
}
} else {
// Not in shuffle mode, go to next song
if (this.settings.myMusicIndex[this.currentTrackIndex + 1]) {
this.currentTrackIndex++;
} else {
this.currentTrackIndex = 0;
}
}
}
this.onSoundscapeChange();
}
/**
* Seek to a specific spot in the song
* @param time
*/
seek(time: number) {
if (this.soundscapeType === SOUNDSCAPE_TYPE.MY_MUSIC) {
this.localPlayer.currentTime = time;
}
}
/**
* Changes the currently playing song when in My Music mode
* @param fileName
*/
changeMyMusicTrack(fileName: string) {
this.currentTrackIndex = this.settings.myMusicIndex.findIndex(
(song) => song.fileName === fileName
);
this.onSoundscapeChange();
}
/**
* Turn on shuffle mode. When we toggle it on, reset the shuffle queue.
*/
toggleShuffle() {
this.settings.myMusicShuffle = !this.settings.myMusicShuffle;
this.saveSettings();
if (this.settings.myMusicShuffle) {
this.shuffleQueue = [];
this.shuffleQueueSpot = 0;
}
}
/**
* Either enables or disables song title scrolling on the mini player depending on the user's settings
*/
toggleNowPlayingScroll() {
if (this.settings.scrollSongTitle) {
this.nowPlayingRoot.removeClass(
"soundscapesroot-nowplaying--noscroll"
);
} else {
this.nowPlayingRoot.addClass(
"soundscapesroot-nowplaying--noscroll"
);
}
}
/**
* Changes the currently playing soundscape and triggers other downstream side effects
* @param soundscape
*/
changeSoundscape(soundscape: string) {
this.settings.soundscape = soundscape;
if (this.settings.soundscape.startsWith(`${SOUNDSCAPE_TYPE.CUSTOM}_`)) {
this.currentTrackIndex = 0;
}
// When we select MY_MUSIC, force a re-index
// Also show the ribbon button!
if (this.settings.soundscape === SOUNDSCAPE_TYPE.MY_MUSIC) {
this.indexMusicLibrary();
this.ribbonButton.show();
} else {
this.ribbonButton.hide();
}
this.onSoundscapeChange();
this.saveSettings();
}
/******************************************************************************************************************/
//#endregion Control Player
/******************************************************************************************************************/
/******************************************************************************************************************/
//#region Events
/******************************************************************************************************************/
/**
* Once the player is ready, create the controls and play some music! (or not if autoplay is disabled)
*/
onPlayerReady() {
this.createControls();
this.onSoundscapeChange(this.settings.autoplay);
}
/**
* Update the UI when the state of the video changes
*/
onStateChange({ data: state }: { data: PLAYER_STATE }) {
const customSoundscape = this.getCurrentCustomSoundscape();
// Next and Previous buttons only apply when we have a playlist-type soundscape
if (this.soundscapeType === SOUNDSCAPE_TYPE.STANDARD) {
this.previousButton.hide();
this.nextButton.hide();
} else {
this.previousButton.show();
this.nextButton.show();
}
switch (state) {
case PLAYER_STATE.UNSTARTED:
this.playButton.show();
this.pauseButton.hide();
break;
case PLAYER_STATE.PLAYING:
this.playButton.hide();
this.pauseButton.show();
this.updateLocalPlayerState({
currentTrack:
this.settings.myMusicIndex[this.currentTrackIndex],
playerState: PLAYER_STATE.PLAYING,
});
break;
case PLAYER_STATE.PAUSED:
this.playButton.show();
this.pauseButton.hide();
this.updateLocalPlayerState({
currentTrack:
this.settings.myMusicIndex[this.currentTrackIndex],
playerState: PLAYER_STATE.PAUSED,
});
break;
case PLAYER_STATE.ENDED:
// When it's a playlist-type soundscape, go to the next song
if (
this.soundscapeType === SOUNDSCAPE_TYPE.CUSTOM ||
this.soundscapeType === SOUNDSCAPE_TYPE.MY_MUSIC
) {
this.next();
}
// For Standard, Loop videos once they end
// For Custom, we'll go to the next track (per above logic)
this.onSoundscapeChange();
}
}
/**
* When we change the volume (usually via the slider), update the player volume, the UI, and save the current volume to settings
*/
onVolumeChange(e: any) {
const volume = parseInt(e.target.value);
this.volumeSlider.value = e.target.value;
this.player?.setVolume(volume);
this.localPlayer.volume = volume / 100; // Audio object expects 0-1
if (volume === 0) {
this.volumeMutedIcon.show();
this.volumeLowIcon.hide();
this.volumeHighIcon.hide();
} else if (volume <= 50) {
this.volumeMutedIcon.hide();
this.volumeLowIcon.show();
this.volumeHighIcon.hide();
} else {
this.volumeMutedIcon.hide();
this.volumeLowIcon.hide();
this.volumeHighIcon.show();
}
this.settings.volume = volume;
// Debounce saves of volume change so we don't hammer the users hard drive
// However, update the observable immediately to keep UI up to date
this.settingsObservable.setValue(this.settings);
this.debouncedSaveSettings();
}
/**
* Play the selected soundscape!
*
* When in My Music mode, the song content is read from the file and base64ed. This is because electron blocks
* local file paths from being used in the Audio element.
*/
onSoundscapeChange(autoplay = true) {
if (this.settings.soundscape.startsWith(`${SOUNDSCAPE_TYPE.CUSTOM}_`)) {
this.soundscapeType = SOUNDSCAPE_TYPE.CUSTOM;
} else if (this.settings.soundscape === SOUNDSCAPE_TYPE.MY_MUSIC) {
this.soundscapeType = SOUNDSCAPE_TYPE.MY_MUSIC;
} else {
this.soundscapeType = SOUNDSCAPE_TYPE.STANDARD;
}
if (this.soundscapeType === SOUNDSCAPE_TYPE.CUSTOM) {
const customSoundscape = this.getCurrentCustomSoundscape();
this.player?.loadVideoById({
videoId: customSoundscape?.tracks[this.currentTrackIndex].id,
});
this.nowPlaying.setText(
customSoundscape?.tracks[this.currentTrackIndex].name || ""
);
if (!autoplay) {
this.player?.pauseVideo();
}
this.statusBarItem.removeClass("soundscapesroot--hideyoutube");
this.localPlayer.pause(); // Edge Case: When switching from MyMusic to Youtube, the youtube video keeps playing
} else if (this.soundscapeType === SOUNDSCAPE_TYPE.MY_MUSIC) {
const track = this.settings.myMusicIndex[this.currentTrackIndex];
if (track) {
const fileData = fs.readFileSync(track.fullPath);
const base64Data = fileData.toString("base64");
this.localPlayer.pause();
this.localPlayer.src = `data:audio/mp3;base64,${base64Data}`;
this.nowPlaying.setText(`${track.title} - ${track.artist}`);
if (autoplay) {
this.localPlayer.play();
} else {
// Need to manually send this cause the state won't be set otherwise
this.onStateChange({ data: PLAYER_STATE.PAUSED });
}
} else {
// We don't have a track (still indexing or empty index)
// Reset the player
this.localPlayer.src = "";
this.nowPlaying.setText("");
this.onStateChange({ data: PLAYER_STATE.PAUSED });
}
this.statusBarItem.addClass("soundscapesroot--hideyoutube");
this.player?.pauseVideo(); // Edge Case: When switching from youtube to MyMusic, the youtube video keeps playing
} else {
this.player?.loadVideoById({
videoId: SOUNDSCAPES[this.settings.soundscape].youtubeId,
});
if (SOUNDSCAPES[this.settings.soundscape].isLiveVideo) {
this.player?.seekTo(this.player.getDuration());
}
this.nowPlaying.setText(
SOUNDSCAPES[this.settings.soundscape].nowPlayingText
);
if (!autoplay) {
this.player?.pauseVideo();
}
this.statusBarItem.removeClass("soundscapesroot--hideyoutube");
this.localPlayer.pause(); // Edge Case: When switching from MyMusic to Youtube, the youtube video keeps playing
}
// Keep miniplayer's soundscape selection button up to date
this.changeSoundscapeSelect.value = this.settings.soundscape;
this.saveSettings();
}
/******************************************************************************************************************/
//#endregion Events
/******************************************************************************************************************/
/******************************************************************************************************************/
//#region Settings and State
/******************************************************************************************************************/
/**
* Load data from disk, stored in data.json in plugin folder
*/
async loadSettings() {
const data = (await this.loadData()) || {};
this.settings = Object.assign({}, DEFAULT_SETTINGS, data);
}
/**
* Save data to disk, stored in data.json in plugin folder
*/
async saveSettings() {
// Persist the current track index
this.settings.currentTrackIndex = this.currentTrackIndex;
this.settingsObservable.setValue(this.settings);
await this.saveData(this.settings);
}
/**
* Merges the update object with the existing local player state
* @param updateObject
*/
updateLocalPlayerState(updateObject: LocalPlayerState) {
this.localPlayerStateObservable.setValue({
...this.localPlayerStateObservable.getValue(),
...updateObject,
});
}
/******************************************************************************************************************/
//#endregion Settings and State
/******************************************************************************************************************/
}