Skip to content

Commit 4ea3de3

Browse files
committed
- playing around with the spotify API
1 parent 0158230 commit 4ea3de3

File tree

1 file changed

+45
-72
lines changed

1 file changed

+45
-72
lines changed

tools/spotify_test.html

Lines changed: 45 additions & 72 deletions
Original file line numberDiff line numberDiff line change
@@ -3,43 +3,19 @@
33
<head>
44
<title>Spotify Dev Player</title>
55
<style>
6-
body {
7-
font-family: Arial, sans-serif;
8-
max-width: 800px;
9-
margin: 2rem auto;
10-
padding: 0 1rem;
11-
}
12-
.credentials {
13-
display: flex;
14-
flex-direction: column;
15-
gap: 1rem;
16-
margin-bottom: 2rem;
17-
}
18-
input {
19-
padding: 0.5rem;
20-
width: 100%;
21-
}
22-
button {
23-
padding: 0.5rem 1rem;
24-
cursor: pointer;
25-
margin: 0.5rem;
26-
}
27-
.hidden {
28-
display: none;
29-
}
30-
#status {
31-
margin: 1rem 0;
32-
padding: 1rem;
33-
background: #f0f0f0;
34-
}
6+
body { font-family: Arial, sans-serif; max-width: 800px; margin: 2rem auto; padding: 0 1rem; }
7+
.credentials { display: flex; flex-direction: column; gap: 1rem; margin-bottom: 2rem; }
8+
input { padding: 0.5rem; width: 100%; }
9+
button { padding: 0.5rem 1rem; cursor: pointer; margin: 0.5rem; }
10+
.hidden { display: none; }
11+
#status { margin: 1rem 0; padding: 1rem; background: #f0f0f0; }
3512
</style>
3613
</head>
3714
<body>
3815
<div id="setup" class="credentials">
3916
<input type="text" id="clientId" placeholder="Enter Spotify Client ID">
4017
<button onclick="startAuth()">Initialize Player</button>
4118
</div>
42-
4319
<div id="player" class="hidden">
4420
<div id="status">Status: Initializing...</div>
4521
<div>
@@ -68,6 +44,11 @@
6844
statusDiv.textContent = `Status: ${message}`;
6945
}
7046

47+
function getUrlParameter(name) {
48+
const urlParams = new URLSearchParams(window.location.search);
49+
return urlParams.get(name);
50+
}
51+
7152
window.onSpotifyWebPlaybackSDKReady = () => {
7253
const params = getHashParams();
7354
if (params.access_token) {
@@ -79,33 +60,24 @@
7960
const clientId = document.getElementById('clientId').value;
8061
const state = Math.random().toString(36).substring(7);
8162
const scope = 'streaming user-read-email user-read-private user-modify-playback-state';
82-
83-
const authUrl = `https://accounts.spotify.com/authorize?client_id=${clientId}` +
84-
`&response_type=token` +
85-
`&redirect_uri=${encodeURIComponent(redirectUri)}` +
86-
`&scope=${encodeURIComponent(scope)}` +
87-
`&state=${state}`;
88-
63+
const authUrl = `https://accounts.spotify.com/authorize?client_id=${clientId}&response_type=token&redirect_uri=${encodeURIComponent(redirectUri)}&scope=${encodeURIComponent(scope)}&state=${state}`;
8964
window.location.href = authUrl;
9065
}
9166

9267
function getHashParams() {
9368
const hashParams = {};
9469
const hash = window.location.hash.substring(1);
9570
const params = hash.split('&');
96-
9771
params.forEach(param => {
9872
const [key, value] = param.split('=');
9973
hashParams[key] = decodeURIComponent(value);
10074
});
101-
10275
return hashParams;
10376
}
10477

10578
function initializePlayer(token) {
10679
document.getElementById('setup').classList.add('hidden');
10780
document.getElementById('player').classList.remove('hidden');
108-
10981
updateStatus('Initializing player...');
11082

11183
playerInstance = new Spotify.Player({
@@ -114,7 +86,6 @@
11486
volume: 0.5
11587
});
11688

117-
// Error handling
11889
playerInstance.addListener('initialization_error', ({ message }) => {
11990
updateStatus(`Initialization Error: ${message}`);
12091
});
@@ -133,22 +104,14 @@
133104
updateStatus(`Playback Error: ${message}`);
134105
});
135106

136-
// Playback status updates
137107
playerInstance.addListener('player_state_changed', state => {
138108
if (state) {
139-
updateStatus(`
140-
Track: ${state.track_window.current_track.name}
141-
Artist: ${state.track_window.current_track.artists[0].name}
142-
Playing: ${!state.paused}
143-
`);
109+
updateStatus(`Track: ${state.track_window.current_track.name} | Artist: ${state.track_window.current_track.artists[0].name} | Playing: ${!state.paused}`);
144110
}
145111
});
146112

147-
// Update the 'ready' listener in initializePlayer():
148113
playerInstance.addListener('ready', ({ device_id }) => {
149114
updateStatus(`Ready with Device ID: ${device_id}`);
150-
151-
// Transfer playback automatically
152115
fetch('https://api.spotify.com/v1/me/player', {
153116
method: 'PUT',
154117
headers: {
@@ -157,31 +120,48 @@
157120
},
158121
body: JSON.stringify({
159122
device_ids: [device_id],
160-
play: false // Set to true if you want to auto-play
123+
play: false
161124
})
162-
})
163-
.then(response => {
164-
if (response.status === 204) {
165-
updateStatus('Successfully transferred playback to this device');
166-
} else {
167-
updateStatus('Failed to transfer playback: ' + response.status);
125+
}).then(response => {
126+
if (response.status === 204) {
127+
updateStatus('Successfully transferred playback');
128+
const trackId = getUrlParameter('track');
129+
if (trackId) {
130+
playTrackById(trackId, token);
168131
}
169-
})
170-
.catch(error => {
171-
updateStatus('Error transferring playback: ' + error);
172-
});
132+
}
133+
});
173134
});
174135

175-
// Not Ready
176136
playerInstance.addListener('not_ready', ({ device_id }) => {
177137
updateStatus(`Device ID has gone offline: ${device_id}`);
178138
});
179139

180-
// Connect to the player
181140
playerInstance.connect();
182141
}
183142

184-
// Player Controls
143+
async function playTrackById(trackId, token) {
144+
try {
145+
const response = await fetch('https://api.spotify.com/v1/me/player/play', {
146+
method: 'PUT',
147+
headers: {
148+
'Authorization': `Bearer ${token}`,
149+
'Content-Type': 'application/json'
150+
},
151+
body: JSON.stringify({
152+
uris: [`spotify:track:${trackId}`]
153+
})
154+
});
155+
if (response.status === 204) {
156+
updateStatus('Started playing track');
157+
} else {
158+
updateStatus('Failed to play track: ' + response.status);
159+
}
160+
} catch (error) {
161+
updateStatus('Error playing track: ' + error);
162+
}
163+
}
164+
185165
async function handlePlay() {
186166
const result = await playerInstance.resume();
187167
updateStatus(`Play result: ${JSON.stringify(result)}`);
@@ -210,12 +190,7 @@
210190
async function getCurrentState() {
211191
const state = await playerInstance.getCurrentState();
212192
if (state) {
213-
updateStatus(`
214-
Current track: ${state.track_window.current_track.name}
215-
Artist: ${state.track_window.current_track.artists[0].name}
216-
Position: ${state.position}
217-
Paused: ${state.paused}
218-
`);
193+
updateStatus(`Current track: ${state.track_window.current_track.name} | Artist: ${state.track_window.current_track.artists[0].name} | Position: ${state.position} | Paused: ${state.paused}`);
219194
} else {
220195
updateStatus('No current state available');
221196
}
@@ -235,7 +210,6 @@
235210
const params = getHashParams();
236211
const token = params.access_token;
237212
const trackUri = document.getElementById('trackUri').value;
238-
239213
try {
240214
const response = await fetch('https://api.spotify.com/v1/me/player/play', {
241215
method: 'PUT',
@@ -247,7 +221,6 @@
247221
uris: [trackUri]
248222
})
249223
});
250-
251224
if (response.status === 204) {
252225
updateStatus('Started playing track');
253226
} else {

0 commit comments

Comments
 (0)