-
Notifications
You must be signed in to change notification settings - Fork 5
/
demo.mjs
53 lines (43 loc) · 1.57 KB
/
demo.mjs
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
import SpotifyPlayer from './index.mjs';
let token = '';
let uri = 'spotify:track:54flyrjcdnQdco7300avMJ';
const loginEl = document.getElementById('login');
const playEl = document.getElementById('play');
const connectEl = document.getElementById('connect');
const playButtonEl = document.getElementById('play-button');
const pauseButtonEl = document.getElementById('pause-button');
const connectButtonEl = document.getElementById('connect-button');
const connectMessageEl = document.getElementById('connect-message');
const spotify = new SpotifyPlayer();
window.addEventListener('DOMContentLoaded', async () => {
const response = await fetch('/test');
const { type, data } = await response.json();
if (type === 'success') {
token = data;
loginEl.style.display = 'none';
connectEl.style.display = 'initial';
}
});
connectButtonEl.addEventListener('click', async () => {
try {
const ret = await spotify.connect(token);
if (ret) {
const playlists = await spotify.getUsersPlaylists();
// Play a random track from the user's favorites.
const idx = Math.floor(Math.random() * playlists[0].tracks.length)
uri = playlists[0].tracks[idx].uri;
playEl.style.display = 'initial';
connectEl.style.display = 'none';
} else {
connectMessageEl.innerHTML = `Error connecting to Spotify`;
}
} catch (err) {
connectMessageEl.innerHTML = `Error connecting to Spotify: ${err.message}`;
}
})
playButtonEl.addEventListener('click', () => {
spotify.play(uri);
});
pauseButtonEl.addEventListener('click', () => {
spotify.pause();
});