Plan
Premium
Country
Australia
Device
Laptop
Operating System
Windows 10
My Question or Issue
I am trying to control the embed player from within my app but it won't autoplay songs. Here is my javascript.. the uri of the song is being loaded correctly, the embed player brings up the track:
<script>
window.onSpotifyWebPlaybackSDKReady = () => {
const token = '<?php echo $accessToken; ?>';
const player = new Spotify.Player({
name: 'Web Playback SDK Quick Start Player',
getOAuthToken: cb => { cb(token); },
volume: 0.5
});
// Ready
player.addListener('ready', ({ device_id }) => {
console.log('Ready with Device ID', device_id);
});
// Not Ready
player.addListener('not_ready', ({ device_id }) => {
console.log('Device ID has gone offline', device_id);
});
player.addListener('initialization_error', ({ message }) => {
console.error(message);
});
player.addListener('authentication_error', ({ message }) => {
console.error(message);
});
player.addListener('account_error', ({ message }) => {
console.error(message);
});
player.connect();
player.activateElement();
// Add a function to handle auto playback
function autoPlayTrack(trackUri) {
player.addListener('ready', ({ device_id }) => {
console.log('Ready with Device ID', device_id);
// Use the Spotify Web Playback SDK to play the track
player._options.getOAuthToken(token => {
fetch(`https://api.spotify.com/v1/me/player/play`, {
method: 'PUT',
body: JSON.stringify({ uris: [`spotify:track:${trackUri}`] }),
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
});
});
});
}
// Get all play button elements
const playButtons = document.querySelectorAll('.play-button');
// Add a click event listener to each play button
playButtons.forEach(playButton => {
playButton.addEventListener('click', () => {
// Get the URI from the data-uri attribute of the clicked play button
const uri = playButton.parentElement.getAttribute('data-uri');
// Get the Spotify Embed Player iframe element
const spotifyPlayer = document.getElementById('spotify-player');
// Update the src attribute with the new URI
spotifyPlayer.src=`https://open.spotify.com/embed/track/${uri}`;
// Call the autoPlayTrack function to play the track
autoPlayTrack(uri);
});
});
};
</script>
My app creates a new access token succesfully and the spotify sdk says its connected in the console. When I click a play button on my site the song does load in the embed player. Is it not possible to have it start playing? I don't want the user to have to click two play buttons.
Thanks
Kias