|
54 | 54 | <button class="setup-button" onclick="startAuth()">Initialize Player</button> |
55 | 55 | </div> |
56 | 56 | <div id="player" class="hidden"> |
57 | | - <button id="playPauseButton">▐▐</button> |
| 57 | + <button id="playPauseButton">▶</button> |
58 | 58 | </div> |
59 | 59 |
|
60 | 60 | <script> |
|
67 | 67 | if (isPlaying) { |
68 | 68 | playerInstance.pause(); |
69 | 69 | } else { |
70 | | - playerInstance.resume(); |
| 70 | + const trackId = getUrlParameter('track'); |
| 71 | + if (trackId) { |
| 72 | + playTrackById(trackId); |
| 73 | + } else { |
| 74 | + playerInstance.resume(); |
| 75 | + } |
71 | 76 | } |
72 | 77 | } |
73 | 78 |
|
|
114 | 119 | return hashParams; |
115 | 120 | } |
116 | 121 |
|
| 122 | + async function playTrackById(trackId) { |
| 123 | + const token = localStorage.getItem('spotify_access_token'); |
| 124 | + try { |
| 125 | + const response = await fetch('https://api.spotify.com/v1/me/player/play', { |
| 126 | + method: 'PUT', |
| 127 | + headers: { |
| 128 | + 'Authorization': `Bearer ${token}`, |
| 129 | + 'Content-Type': 'application/json' |
| 130 | + }, |
| 131 | + body: JSON.stringify({ |
| 132 | + uris: [`spotify:track:${trackId}`] |
| 133 | + }) |
| 134 | + }); |
| 135 | + if (response.status === 204) { |
| 136 | + updatePlayPauseButton(true); |
| 137 | + } |
| 138 | + } catch (error) { |
| 139 | + console.error('Error playing track:', error); |
| 140 | + } |
| 141 | + } |
| 142 | + |
117 | 143 | function initializePlayer(token) { |
118 | 144 | document.getElementById('setup').classList.add('hidden'); |
119 | 145 | document.getElementById('player').classList.remove('hidden'); |
|
140 | 166 | } |
141 | 167 | }); |
142 | 168 |
|
143 | | - let deviceReady = false; |
144 | 169 | playerInstance.addListener('ready', async ({ device_id }) => { |
145 | | - deviceReady = true; |
146 | 170 | try { |
147 | 171 | await fetch('https://api.spotify.com/v1/me/player', { |
148 | 172 | method: 'PUT', |
|
155 | 179 | play: false |
156 | 180 | }) |
157 | 181 | }); |
158 | | - |
159 | | - const trackId = getUrlParameter('track'); |
160 | | - if (trackId) { |
161 | | - await new Promise(resolve => setTimeout(resolve, 1000)); |
162 | | - await fetch('https://api.spotify.com/v1/me/player/play', { |
163 | | - method: 'PUT', |
164 | | - headers: { |
165 | | - 'Authorization': `Bearer ${token}`, |
166 | | - 'Content-Type': 'application/json' |
167 | | - }, |
168 | | - body: JSON.stringify({ |
169 | | - uris: [`spotify:track:${trackId}`] |
170 | | - }) |
171 | | - }); |
172 | | - updatePlayPauseButton(true); |
173 | | - } |
174 | 182 | } catch (error) { |
175 | 183 | console.error('Error during player initialization:', error); |
176 | 184 | } |
|
0 commit comments