Disable autoplay on spotify SDK












0















I've integrated web playback SDK of Spotify on my website allowing my users to login via their spotify accounts and play music.



However, the issue is, music gets played as soon as page is loaded. I want this to happen when the play button is hit.



Here's the JS code I've written



/**
* Convert milliseconds to minutes
*/
function millisToMinutesAndSeconds(millis) {
var minutes = Math.floor(millis / 60000);
var seconds = ((millis % 60000) / 1000).toFixed(0);
return minutes + ":" + (seconds < 10 ? '0' : '') + seconds;
}

jQuery( document ).ready(function() {
console.log( "ready!" );
});

/**
* Callback for Spotify when SDK is ready
*/
window.onSpotifyWebPlaybackSDKReady = () => {
const player = new Spotify.Player({
name: 'Web Playback SDK Quick Start Player',
getOAuthToken: cb => { cb(token); },
volume: 0.8
});
var setintId = 0;
var progressMs = 0;
var progressBar = jQuery('#song-progress .noUi-origin');
// Playback status updates
player.addListener('player_state_changed', state => {
if (state != null) {
jQuery('.current-track__progress__finish').text(millisToMinutesAndSeconds(state.duration));
if (state.paused) {
jQuery('.current-track').find('.play').addClass('ion-ios-play').removeClass('ion-ios-pause');
} else {
jQuery('.current-track').find('.play').addClass('ion-ios-pause').removeClass('ion-ios-play');
}
clearInterval(setintId);
progressMs = state.position;
// progress bar logic
if (state.paused == false) {
setintId = setInterval(function (state) {
progressMs += 1000;
let progressPercentage = progressMs / state.duration * 100;
document.getElementById('song-progress').noUiSlider.set(progressPercentage);

//progressBar.css('left',progressPercentage.toFixed(1) + '%');
jQuery('.current-track__progress__start').text(millisToMinutesAndSeconds(progressMs));
if (progressMs >= state.duration) {
clearInterval(setintId);
}
}, 1000, state);
}
}
});

// Seek to a minute into the track
progressBar.find('.noUi-handle').on('mousedown',function(){
clearInterval(setintId);
});
progressBar.find('.noUi-handle').on('mouseup',function(){
player.getCurrentState().then(state => {
if (!state) {
console.error('User is not playing music through the Web Playback SDK');
return;
}
var percentage = parseInt(progressBar.css('left')) / parseInt(progressBar.parent().width()) * 100;
document.getElementById('song-progress').noUiSlider.set(percentage);
var seekTo = ( parseInt( percentage ) / 100 ) * state.duration;
player.seek(seekTo).then(() => {
console.log('Changed position!');
});
});
});

// Error handling
player.addListener('initialization_error', ({ message }) => { alert(message); });
player.addListener('authentication_error', ({ message }) => { alert(message); });
player.addListener('account_error', ({ message }) => { alert(message); });
player.addListener('playback_error', ({ message }) => { alert(message); });


// Ready
player.addListener('ready', ({ device_id }) => {
var playerSkin = jQuery('.current-track');
var trackList = jQuery('.tracks');
var tracks = ;

if (typeof search_artist !== "undefined") {
fetch('https://api.spotify.com/v1/search/?q=' + search_artist + '&type=artist', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token
},
}).then(function(response) {
return response.json();
}).then((response)=>{
var artists = response.artists;
var firstItemId = artists.items[0].id;
getTopTenTracks(firstItemId);
}).catch((error)=>{
console.log('error',error);
});
}

function getTopTenTracks(artistID) {
fetch('https://api.spotify.com/v1/artists/'+ artistID +'/top-tracks?market=from_token', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token
},
}).then(function(response) {
return response.json();
}).then((response)=>{
var tracksGot = response.tracks;
parseTracksList(tracksGot);
trackList = jQuery('.tracks');
trackList.find('.track').each(function(){
tracks.push(jQuery(this).data('uri'));
});

// setUpListeners();
fetch('https://api.spotify.com/v1/me/player/play?device_id=' + device_id, {
method: 'PUT',
body: JSON.stringify({uris: tracks}),
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token
},
}).then(function (response) {
setUpListeners();
});
}).catch((error)=>{
console.log('error',error);
});
}

function parseTracksList(tracks) {
for (var i = 0; i < tracks.length; i++) {
appendTrackToHtml(tracks[i],i);
}
}

var artistContent = document.getElementById('search_artist_content');

function appendTrackToHtml(track, iterator) {
var wrapper = document.createElement('div');
wrapper.className='tracks songTrack';
var trackDiv = document.createElement('div');
trackDiv.className = 'track';
trackDiv.setAttribute('data-uri',track.uri);

var imgWrapper = document.createElement('div');
imgWrapper.className = 'track__art';
var trackArt = document.createElement("img");
trackArt.src = track.album.images[2].url;
imgWrapper.appendChild(trackArt);
trackDiv.appendChild(imgWrapper);

var counter = document.createElement('div');
counter.className = 'track__number';
counter.append(iterator);
trackDiv.append(counter);

var checkMarkWrap = document.createElement('div');
checkMarkWrap.className = 'track__added';
var icon = document.createElement('i');
icon.className = 'ion-checkmark-round added';
checkMarkWrap.appendChild(icon);
trackDiv.appendChild(checkMarkWrap);

var trackTitle = document.createElement('div');
trackTitle.className = 'track__title';
trackTitle.append(track.name);
trackDiv.appendChild(trackTitle);

wrapper.appendChild(trackDiv);
artistContent.appendChild(wrapper);
}

if (typeof search_artist === "undefined") {
trackList.find('.track').each(function(){
tracks.push(jQuery(this).data('uri'));
});

//Start to play
fetch('https://api.spotify.com/v1/me/player/play?device_id=' + device_id, {
method: 'PUT',
body: JSON.stringify({uris: tracks}),
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token
},
});

setUpListeners();
}

function setUpListeners() {

// Change track from OverView list
trackList.on('click','.track',function(){

fetch('https://api.spotify.com/v1/me/player/play?device_id=' + device_id, {
method: 'PUT',
body: JSON.stringify({ uris: [jQuery(this).data('uri')] }),
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token
},
});

});

// Start to play all tracks by clicking play button of artist
jQuery('.artist__info__actions button.button-dark').on('click', function () {

fetch('https://api.spotify.com/v1/me/player/play?device_id=' + device_id, {
method: 'PUT',
body: JSON.stringify({uris: tracks}),
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token
},
});

});


//Play button
playerSkin.find('.play').on('click', function () {
jQuery(this).toggleClass('ion-ios-play ion-ios-pause');
console.log('play clicked');
player.togglePlay().then(() => {
console.log('Toggled playback!');
});
});

//Volume button
playerSkin.find('#song-volume .noUi-origin').on('mouseup', function () {
let width = parseInt(playerSkin.find('#song-volume .noUi-base').width());
let volume = parseInt(jQuery(this).css('left')) / width;

player.setVolume(volume.toFixed(1)).then(() => {
// Switch buttons
if (volume == 0) {
playerSkin.find('.control.volume i').addClass('ion-volume-mute').removeClass('ion-volume-hight');
} else {
playerSkin.find('.control.volume i').addClass('ion-volume-hight').removeClass('ion-volume-mute');
}
});
});

//Mute button
playerSkin.on('click', '.control.volume i.ion-volume-high', function () {
player.setVolume(0).then(() => {
playerSkin.find('.control.volume i').addClass('ion-volume-mute').removeClass('ion-volume-high');
playerSkin.find('#song-volume .noUi-origin').css('left', '0%');
});
});

//Unmute button
playerSkin.on('click', '.control.volume i.ion-volume-mute', function () {
player.setVolume(0.5).then(() => {
playerSkin.find('.control.volume i').addClass('ion-volume-high').removeClass('ion-volume-mute');
playerSkin.find('#song-volume .noUi-origin').css('left', '50%');
});
});

// Next track
playerSkin.find('.ion-ios-skipforward').on('click', function () {
player.nextTrack().then(() => {
console.log('Skipped to next track!');
});
});


//Prev track
playerSkin.find('.ion-ios-skipbackward').on('click', function () {
player.previousTrack().then(() => {
console.log('Set to previous track!');
});
});

// Change position and Duration
player.addListener('player_state_changed', ({
position,
duration,
track_window: {current_track}
}) => {
jQuery('.playing__song__name').text(current_track.name);
jQuery('.playing__song__artist').text(current_track.artists[0].name);
jQuery('.playing__art img').attr('src', current_track.album.images[0].url);
//Set active item in list
trackList.find('.track').removeClass('playing');
trackList.find('[data-uri="' + current_track.uri + '"]').addClass('playing');
});
}

});

// Connect to the player!
player.connect();
};


Any guidance would be appreciated.










share|improve this question























  • I'm currently stuck on the exact same problem for iOS, so interested to hear from anyone if this possible on any of the APIs.

    – Benjamin Lowry
    Nov 20 '18 at 8:06
















0















I've integrated web playback SDK of Spotify on my website allowing my users to login via their spotify accounts and play music.



However, the issue is, music gets played as soon as page is loaded. I want this to happen when the play button is hit.



Here's the JS code I've written



/**
* Convert milliseconds to minutes
*/
function millisToMinutesAndSeconds(millis) {
var minutes = Math.floor(millis / 60000);
var seconds = ((millis % 60000) / 1000).toFixed(0);
return minutes + ":" + (seconds < 10 ? '0' : '') + seconds;
}

jQuery( document ).ready(function() {
console.log( "ready!" );
});

/**
* Callback for Spotify when SDK is ready
*/
window.onSpotifyWebPlaybackSDKReady = () => {
const player = new Spotify.Player({
name: 'Web Playback SDK Quick Start Player',
getOAuthToken: cb => { cb(token); },
volume: 0.8
});
var setintId = 0;
var progressMs = 0;
var progressBar = jQuery('#song-progress .noUi-origin');
// Playback status updates
player.addListener('player_state_changed', state => {
if (state != null) {
jQuery('.current-track__progress__finish').text(millisToMinutesAndSeconds(state.duration));
if (state.paused) {
jQuery('.current-track').find('.play').addClass('ion-ios-play').removeClass('ion-ios-pause');
} else {
jQuery('.current-track').find('.play').addClass('ion-ios-pause').removeClass('ion-ios-play');
}
clearInterval(setintId);
progressMs = state.position;
// progress bar logic
if (state.paused == false) {
setintId = setInterval(function (state) {
progressMs += 1000;
let progressPercentage = progressMs / state.duration * 100;
document.getElementById('song-progress').noUiSlider.set(progressPercentage);

//progressBar.css('left',progressPercentage.toFixed(1) + '%');
jQuery('.current-track__progress__start').text(millisToMinutesAndSeconds(progressMs));
if (progressMs >= state.duration) {
clearInterval(setintId);
}
}, 1000, state);
}
}
});

// Seek to a minute into the track
progressBar.find('.noUi-handle').on('mousedown',function(){
clearInterval(setintId);
});
progressBar.find('.noUi-handle').on('mouseup',function(){
player.getCurrentState().then(state => {
if (!state) {
console.error('User is not playing music through the Web Playback SDK');
return;
}
var percentage = parseInt(progressBar.css('left')) / parseInt(progressBar.parent().width()) * 100;
document.getElementById('song-progress').noUiSlider.set(percentage);
var seekTo = ( parseInt( percentage ) / 100 ) * state.duration;
player.seek(seekTo).then(() => {
console.log('Changed position!');
});
});
});

// Error handling
player.addListener('initialization_error', ({ message }) => { alert(message); });
player.addListener('authentication_error', ({ message }) => { alert(message); });
player.addListener('account_error', ({ message }) => { alert(message); });
player.addListener('playback_error', ({ message }) => { alert(message); });


// Ready
player.addListener('ready', ({ device_id }) => {
var playerSkin = jQuery('.current-track');
var trackList = jQuery('.tracks');
var tracks = ;

if (typeof search_artist !== "undefined") {
fetch('https://api.spotify.com/v1/search/?q=' + search_artist + '&type=artist', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token
},
}).then(function(response) {
return response.json();
}).then((response)=>{
var artists = response.artists;
var firstItemId = artists.items[0].id;
getTopTenTracks(firstItemId);
}).catch((error)=>{
console.log('error',error);
});
}

function getTopTenTracks(artistID) {
fetch('https://api.spotify.com/v1/artists/'+ artistID +'/top-tracks?market=from_token', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token
},
}).then(function(response) {
return response.json();
}).then((response)=>{
var tracksGot = response.tracks;
parseTracksList(tracksGot);
trackList = jQuery('.tracks');
trackList.find('.track').each(function(){
tracks.push(jQuery(this).data('uri'));
});

// setUpListeners();
fetch('https://api.spotify.com/v1/me/player/play?device_id=' + device_id, {
method: 'PUT',
body: JSON.stringify({uris: tracks}),
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token
},
}).then(function (response) {
setUpListeners();
});
}).catch((error)=>{
console.log('error',error);
});
}

function parseTracksList(tracks) {
for (var i = 0; i < tracks.length; i++) {
appendTrackToHtml(tracks[i],i);
}
}

var artistContent = document.getElementById('search_artist_content');

function appendTrackToHtml(track, iterator) {
var wrapper = document.createElement('div');
wrapper.className='tracks songTrack';
var trackDiv = document.createElement('div');
trackDiv.className = 'track';
trackDiv.setAttribute('data-uri',track.uri);

var imgWrapper = document.createElement('div');
imgWrapper.className = 'track__art';
var trackArt = document.createElement("img");
trackArt.src = track.album.images[2].url;
imgWrapper.appendChild(trackArt);
trackDiv.appendChild(imgWrapper);

var counter = document.createElement('div');
counter.className = 'track__number';
counter.append(iterator);
trackDiv.append(counter);

var checkMarkWrap = document.createElement('div');
checkMarkWrap.className = 'track__added';
var icon = document.createElement('i');
icon.className = 'ion-checkmark-round added';
checkMarkWrap.appendChild(icon);
trackDiv.appendChild(checkMarkWrap);

var trackTitle = document.createElement('div');
trackTitle.className = 'track__title';
trackTitle.append(track.name);
trackDiv.appendChild(trackTitle);

wrapper.appendChild(trackDiv);
artistContent.appendChild(wrapper);
}

if (typeof search_artist === "undefined") {
trackList.find('.track').each(function(){
tracks.push(jQuery(this).data('uri'));
});

//Start to play
fetch('https://api.spotify.com/v1/me/player/play?device_id=' + device_id, {
method: 'PUT',
body: JSON.stringify({uris: tracks}),
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token
},
});

setUpListeners();
}

function setUpListeners() {

// Change track from OverView list
trackList.on('click','.track',function(){

fetch('https://api.spotify.com/v1/me/player/play?device_id=' + device_id, {
method: 'PUT',
body: JSON.stringify({ uris: [jQuery(this).data('uri')] }),
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token
},
});

});

// Start to play all tracks by clicking play button of artist
jQuery('.artist__info__actions button.button-dark').on('click', function () {

fetch('https://api.spotify.com/v1/me/player/play?device_id=' + device_id, {
method: 'PUT',
body: JSON.stringify({uris: tracks}),
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token
},
});

});


//Play button
playerSkin.find('.play').on('click', function () {
jQuery(this).toggleClass('ion-ios-play ion-ios-pause');
console.log('play clicked');
player.togglePlay().then(() => {
console.log('Toggled playback!');
});
});

//Volume button
playerSkin.find('#song-volume .noUi-origin').on('mouseup', function () {
let width = parseInt(playerSkin.find('#song-volume .noUi-base').width());
let volume = parseInt(jQuery(this).css('left')) / width;

player.setVolume(volume.toFixed(1)).then(() => {
// Switch buttons
if (volume == 0) {
playerSkin.find('.control.volume i').addClass('ion-volume-mute').removeClass('ion-volume-hight');
} else {
playerSkin.find('.control.volume i').addClass('ion-volume-hight').removeClass('ion-volume-mute');
}
});
});

//Mute button
playerSkin.on('click', '.control.volume i.ion-volume-high', function () {
player.setVolume(0).then(() => {
playerSkin.find('.control.volume i').addClass('ion-volume-mute').removeClass('ion-volume-high');
playerSkin.find('#song-volume .noUi-origin').css('left', '0%');
});
});

//Unmute button
playerSkin.on('click', '.control.volume i.ion-volume-mute', function () {
player.setVolume(0.5).then(() => {
playerSkin.find('.control.volume i').addClass('ion-volume-high').removeClass('ion-volume-mute');
playerSkin.find('#song-volume .noUi-origin').css('left', '50%');
});
});

// Next track
playerSkin.find('.ion-ios-skipforward').on('click', function () {
player.nextTrack().then(() => {
console.log('Skipped to next track!');
});
});


//Prev track
playerSkin.find('.ion-ios-skipbackward').on('click', function () {
player.previousTrack().then(() => {
console.log('Set to previous track!');
});
});

// Change position and Duration
player.addListener('player_state_changed', ({
position,
duration,
track_window: {current_track}
}) => {
jQuery('.playing__song__name').text(current_track.name);
jQuery('.playing__song__artist').text(current_track.artists[0].name);
jQuery('.playing__art img').attr('src', current_track.album.images[0].url);
//Set active item in list
trackList.find('.track').removeClass('playing');
trackList.find('[data-uri="' + current_track.uri + '"]').addClass('playing');
});
}

});

// Connect to the player!
player.connect();
};


Any guidance would be appreciated.










share|improve this question























  • I'm currently stuck on the exact same problem for iOS, so interested to hear from anyone if this possible on any of the APIs.

    – Benjamin Lowry
    Nov 20 '18 at 8:06














0












0








0








I've integrated web playback SDK of Spotify on my website allowing my users to login via their spotify accounts and play music.



However, the issue is, music gets played as soon as page is loaded. I want this to happen when the play button is hit.



Here's the JS code I've written



/**
* Convert milliseconds to minutes
*/
function millisToMinutesAndSeconds(millis) {
var minutes = Math.floor(millis / 60000);
var seconds = ((millis % 60000) / 1000).toFixed(0);
return minutes + ":" + (seconds < 10 ? '0' : '') + seconds;
}

jQuery( document ).ready(function() {
console.log( "ready!" );
});

/**
* Callback for Spotify when SDK is ready
*/
window.onSpotifyWebPlaybackSDKReady = () => {
const player = new Spotify.Player({
name: 'Web Playback SDK Quick Start Player',
getOAuthToken: cb => { cb(token); },
volume: 0.8
});
var setintId = 0;
var progressMs = 0;
var progressBar = jQuery('#song-progress .noUi-origin');
// Playback status updates
player.addListener('player_state_changed', state => {
if (state != null) {
jQuery('.current-track__progress__finish').text(millisToMinutesAndSeconds(state.duration));
if (state.paused) {
jQuery('.current-track').find('.play').addClass('ion-ios-play').removeClass('ion-ios-pause');
} else {
jQuery('.current-track').find('.play').addClass('ion-ios-pause').removeClass('ion-ios-play');
}
clearInterval(setintId);
progressMs = state.position;
// progress bar logic
if (state.paused == false) {
setintId = setInterval(function (state) {
progressMs += 1000;
let progressPercentage = progressMs / state.duration * 100;
document.getElementById('song-progress').noUiSlider.set(progressPercentage);

//progressBar.css('left',progressPercentage.toFixed(1) + '%');
jQuery('.current-track__progress__start').text(millisToMinutesAndSeconds(progressMs));
if (progressMs >= state.duration) {
clearInterval(setintId);
}
}, 1000, state);
}
}
});

// Seek to a minute into the track
progressBar.find('.noUi-handle').on('mousedown',function(){
clearInterval(setintId);
});
progressBar.find('.noUi-handle').on('mouseup',function(){
player.getCurrentState().then(state => {
if (!state) {
console.error('User is not playing music through the Web Playback SDK');
return;
}
var percentage = parseInt(progressBar.css('left')) / parseInt(progressBar.parent().width()) * 100;
document.getElementById('song-progress').noUiSlider.set(percentage);
var seekTo = ( parseInt( percentage ) / 100 ) * state.duration;
player.seek(seekTo).then(() => {
console.log('Changed position!');
});
});
});

// Error handling
player.addListener('initialization_error', ({ message }) => { alert(message); });
player.addListener('authentication_error', ({ message }) => { alert(message); });
player.addListener('account_error', ({ message }) => { alert(message); });
player.addListener('playback_error', ({ message }) => { alert(message); });


// Ready
player.addListener('ready', ({ device_id }) => {
var playerSkin = jQuery('.current-track');
var trackList = jQuery('.tracks');
var tracks = ;

if (typeof search_artist !== "undefined") {
fetch('https://api.spotify.com/v1/search/?q=' + search_artist + '&type=artist', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token
},
}).then(function(response) {
return response.json();
}).then((response)=>{
var artists = response.artists;
var firstItemId = artists.items[0].id;
getTopTenTracks(firstItemId);
}).catch((error)=>{
console.log('error',error);
});
}

function getTopTenTracks(artistID) {
fetch('https://api.spotify.com/v1/artists/'+ artistID +'/top-tracks?market=from_token', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token
},
}).then(function(response) {
return response.json();
}).then((response)=>{
var tracksGot = response.tracks;
parseTracksList(tracksGot);
trackList = jQuery('.tracks');
trackList.find('.track').each(function(){
tracks.push(jQuery(this).data('uri'));
});

// setUpListeners();
fetch('https://api.spotify.com/v1/me/player/play?device_id=' + device_id, {
method: 'PUT',
body: JSON.stringify({uris: tracks}),
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token
},
}).then(function (response) {
setUpListeners();
});
}).catch((error)=>{
console.log('error',error);
});
}

function parseTracksList(tracks) {
for (var i = 0; i < tracks.length; i++) {
appendTrackToHtml(tracks[i],i);
}
}

var artistContent = document.getElementById('search_artist_content');

function appendTrackToHtml(track, iterator) {
var wrapper = document.createElement('div');
wrapper.className='tracks songTrack';
var trackDiv = document.createElement('div');
trackDiv.className = 'track';
trackDiv.setAttribute('data-uri',track.uri);

var imgWrapper = document.createElement('div');
imgWrapper.className = 'track__art';
var trackArt = document.createElement("img");
trackArt.src = track.album.images[2].url;
imgWrapper.appendChild(trackArt);
trackDiv.appendChild(imgWrapper);

var counter = document.createElement('div');
counter.className = 'track__number';
counter.append(iterator);
trackDiv.append(counter);

var checkMarkWrap = document.createElement('div');
checkMarkWrap.className = 'track__added';
var icon = document.createElement('i');
icon.className = 'ion-checkmark-round added';
checkMarkWrap.appendChild(icon);
trackDiv.appendChild(checkMarkWrap);

var trackTitle = document.createElement('div');
trackTitle.className = 'track__title';
trackTitle.append(track.name);
trackDiv.appendChild(trackTitle);

wrapper.appendChild(trackDiv);
artistContent.appendChild(wrapper);
}

if (typeof search_artist === "undefined") {
trackList.find('.track').each(function(){
tracks.push(jQuery(this).data('uri'));
});

//Start to play
fetch('https://api.spotify.com/v1/me/player/play?device_id=' + device_id, {
method: 'PUT',
body: JSON.stringify({uris: tracks}),
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token
},
});

setUpListeners();
}

function setUpListeners() {

// Change track from OverView list
trackList.on('click','.track',function(){

fetch('https://api.spotify.com/v1/me/player/play?device_id=' + device_id, {
method: 'PUT',
body: JSON.stringify({ uris: [jQuery(this).data('uri')] }),
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token
},
});

});

// Start to play all tracks by clicking play button of artist
jQuery('.artist__info__actions button.button-dark').on('click', function () {

fetch('https://api.spotify.com/v1/me/player/play?device_id=' + device_id, {
method: 'PUT',
body: JSON.stringify({uris: tracks}),
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token
},
});

});


//Play button
playerSkin.find('.play').on('click', function () {
jQuery(this).toggleClass('ion-ios-play ion-ios-pause');
console.log('play clicked');
player.togglePlay().then(() => {
console.log('Toggled playback!');
});
});

//Volume button
playerSkin.find('#song-volume .noUi-origin').on('mouseup', function () {
let width = parseInt(playerSkin.find('#song-volume .noUi-base').width());
let volume = parseInt(jQuery(this).css('left')) / width;

player.setVolume(volume.toFixed(1)).then(() => {
// Switch buttons
if (volume == 0) {
playerSkin.find('.control.volume i').addClass('ion-volume-mute').removeClass('ion-volume-hight');
} else {
playerSkin.find('.control.volume i').addClass('ion-volume-hight').removeClass('ion-volume-mute');
}
});
});

//Mute button
playerSkin.on('click', '.control.volume i.ion-volume-high', function () {
player.setVolume(0).then(() => {
playerSkin.find('.control.volume i').addClass('ion-volume-mute').removeClass('ion-volume-high');
playerSkin.find('#song-volume .noUi-origin').css('left', '0%');
});
});

//Unmute button
playerSkin.on('click', '.control.volume i.ion-volume-mute', function () {
player.setVolume(0.5).then(() => {
playerSkin.find('.control.volume i').addClass('ion-volume-high').removeClass('ion-volume-mute');
playerSkin.find('#song-volume .noUi-origin').css('left', '50%');
});
});

// Next track
playerSkin.find('.ion-ios-skipforward').on('click', function () {
player.nextTrack().then(() => {
console.log('Skipped to next track!');
});
});


//Prev track
playerSkin.find('.ion-ios-skipbackward').on('click', function () {
player.previousTrack().then(() => {
console.log('Set to previous track!');
});
});

// Change position and Duration
player.addListener('player_state_changed', ({
position,
duration,
track_window: {current_track}
}) => {
jQuery('.playing__song__name').text(current_track.name);
jQuery('.playing__song__artist').text(current_track.artists[0].name);
jQuery('.playing__art img').attr('src', current_track.album.images[0].url);
//Set active item in list
trackList.find('.track').removeClass('playing');
trackList.find('[data-uri="' + current_track.uri + '"]').addClass('playing');
});
}

});

// Connect to the player!
player.connect();
};


Any guidance would be appreciated.










share|improve this question














I've integrated web playback SDK of Spotify on my website allowing my users to login via their spotify accounts and play music.



However, the issue is, music gets played as soon as page is loaded. I want this to happen when the play button is hit.



Here's the JS code I've written



/**
* Convert milliseconds to minutes
*/
function millisToMinutesAndSeconds(millis) {
var minutes = Math.floor(millis / 60000);
var seconds = ((millis % 60000) / 1000).toFixed(0);
return minutes + ":" + (seconds < 10 ? '0' : '') + seconds;
}

jQuery( document ).ready(function() {
console.log( "ready!" );
});

/**
* Callback for Spotify when SDK is ready
*/
window.onSpotifyWebPlaybackSDKReady = () => {
const player = new Spotify.Player({
name: 'Web Playback SDK Quick Start Player',
getOAuthToken: cb => { cb(token); },
volume: 0.8
});
var setintId = 0;
var progressMs = 0;
var progressBar = jQuery('#song-progress .noUi-origin');
// Playback status updates
player.addListener('player_state_changed', state => {
if (state != null) {
jQuery('.current-track__progress__finish').text(millisToMinutesAndSeconds(state.duration));
if (state.paused) {
jQuery('.current-track').find('.play').addClass('ion-ios-play').removeClass('ion-ios-pause');
} else {
jQuery('.current-track').find('.play').addClass('ion-ios-pause').removeClass('ion-ios-play');
}
clearInterval(setintId);
progressMs = state.position;
// progress bar logic
if (state.paused == false) {
setintId = setInterval(function (state) {
progressMs += 1000;
let progressPercentage = progressMs / state.duration * 100;
document.getElementById('song-progress').noUiSlider.set(progressPercentage);

//progressBar.css('left',progressPercentage.toFixed(1) + '%');
jQuery('.current-track__progress__start').text(millisToMinutesAndSeconds(progressMs));
if (progressMs >= state.duration) {
clearInterval(setintId);
}
}, 1000, state);
}
}
});

// Seek to a minute into the track
progressBar.find('.noUi-handle').on('mousedown',function(){
clearInterval(setintId);
});
progressBar.find('.noUi-handle').on('mouseup',function(){
player.getCurrentState().then(state => {
if (!state) {
console.error('User is not playing music through the Web Playback SDK');
return;
}
var percentage = parseInt(progressBar.css('left')) / parseInt(progressBar.parent().width()) * 100;
document.getElementById('song-progress').noUiSlider.set(percentage);
var seekTo = ( parseInt( percentage ) / 100 ) * state.duration;
player.seek(seekTo).then(() => {
console.log('Changed position!');
});
});
});

// Error handling
player.addListener('initialization_error', ({ message }) => { alert(message); });
player.addListener('authentication_error', ({ message }) => { alert(message); });
player.addListener('account_error', ({ message }) => { alert(message); });
player.addListener('playback_error', ({ message }) => { alert(message); });


// Ready
player.addListener('ready', ({ device_id }) => {
var playerSkin = jQuery('.current-track');
var trackList = jQuery('.tracks');
var tracks = ;

if (typeof search_artist !== "undefined") {
fetch('https://api.spotify.com/v1/search/?q=' + search_artist + '&type=artist', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token
},
}).then(function(response) {
return response.json();
}).then((response)=>{
var artists = response.artists;
var firstItemId = artists.items[0].id;
getTopTenTracks(firstItemId);
}).catch((error)=>{
console.log('error',error);
});
}

function getTopTenTracks(artistID) {
fetch('https://api.spotify.com/v1/artists/'+ artistID +'/top-tracks?market=from_token', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token
},
}).then(function(response) {
return response.json();
}).then((response)=>{
var tracksGot = response.tracks;
parseTracksList(tracksGot);
trackList = jQuery('.tracks');
trackList.find('.track').each(function(){
tracks.push(jQuery(this).data('uri'));
});

// setUpListeners();
fetch('https://api.spotify.com/v1/me/player/play?device_id=' + device_id, {
method: 'PUT',
body: JSON.stringify({uris: tracks}),
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token
},
}).then(function (response) {
setUpListeners();
});
}).catch((error)=>{
console.log('error',error);
});
}

function parseTracksList(tracks) {
for (var i = 0; i < tracks.length; i++) {
appendTrackToHtml(tracks[i],i);
}
}

var artistContent = document.getElementById('search_artist_content');

function appendTrackToHtml(track, iterator) {
var wrapper = document.createElement('div');
wrapper.className='tracks songTrack';
var trackDiv = document.createElement('div');
trackDiv.className = 'track';
trackDiv.setAttribute('data-uri',track.uri);

var imgWrapper = document.createElement('div');
imgWrapper.className = 'track__art';
var trackArt = document.createElement("img");
trackArt.src = track.album.images[2].url;
imgWrapper.appendChild(trackArt);
trackDiv.appendChild(imgWrapper);

var counter = document.createElement('div');
counter.className = 'track__number';
counter.append(iterator);
trackDiv.append(counter);

var checkMarkWrap = document.createElement('div');
checkMarkWrap.className = 'track__added';
var icon = document.createElement('i');
icon.className = 'ion-checkmark-round added';
checkMarkWrap.appendChild(icon);
trackDiv.appendChild(checkMarkWrap);

var trackTitle = document.createElement('div');
trackTitle.className = 'track__title';
trackTitle.append(track.name);
trackDiv.appendChild(trackTitle);

wrapper.appendChild(trackDiv);
artistContent.appendChild(wrapper);
}

if (typeof search_artist === "undefined") {
trackList.find('.track').each(function(){
tracks.push(jQuery(this).data('uri'));
});

//Start to play
fetch('https://api.spotify.com/v1/me/player/play?device_id=' + device_id, {
method: 'PUT',
body: JSON.stringify({uris: tracks}),
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token
},
});

setUpListeners();
}

function setUpListeners() {

// Change track from OverView list
trackList.on('click','.track',function(){

fetch('https://api.spotify.com/v1/me/player/play?device_id=' + device_id, {
method: 'PUT',
body: JSON.stringify({ uris: [jQuery(this).data('uri')] }),
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token
},
});

});

// Start to play all tracks by clicking play button of artist
jQuery('.artist__info__actions button.button-dark').on('click', function () {

fetch('https://api.spotify.com/v1/me/player/play?device_id=' + device_id, {
method: 'PUT',
body: JSON.stringify({uris: tracks}),
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token
},
});

});


//Play button
playerSkin.find('.play').on('click', function () {
jQuery(this).toggleClass('ion-ios-play ion-ios-pause');
console.log('play clicked');
player.togglePlay().then(() => {
console.log('Toggled playback!');
});
});

//Volume button
playerSkin.find('#song-volume .noUi-origin').on('mouseup', function () {
let width = parseInt(playerSkin.find('#song-volume .noUi-base').width());
let volume = parseInt(jQuery(this).css('left')) / width;

player.setVolume(volume.toFixed(1)).then(() => {
// Switch buttons
if (volume == 0) {
playerSkin.find('.control.volume i').addClass('ion-volume-mute').removeClass('ion-volume-hight');
} else {
playerSkin.find('.control.volume i').addClass('ion-volume-hight').removeClass('ion-volume-mute');
}
});
});

//Mute button
playerSkin.on('click', '.control.volume i.ion-volume-high', function () {
player.setVolume(0).then(() => {
playerSkin.find('.control.volume i').addClass('ion-volume-mute').removeClass('ion-volume-high');
playerSkin.find('#song-volume .noUi-origin').css('left', '0%');
});
});

//Unmute button
playerSkin.on('click', '.control.volume i.ion-volume-mute', function () {
player.setVolume(0.5).then(() => {
playerSkin.find('.control.volume i').addClass('ion-volume-high').removeClass('ion-volume-mute');
playerSkin.find('#song-volume .noUi-origin').css('left', '50%');
});
});

// Next track
playerSkin.find('.ion-ios-skipforward').on('click', function () {
player.nextTrack().then(() => {
console.log('Skipped to next track!');
});
});


//Prev track
playerSkin.find('.ion-ios-skipbackward').on('click', function () {
player.previousTrack().then(() => {
console.log('Set to previous track!');
});
});

// Change position and Duration
player.addListener('player_state_changed', ({
position,
duration,
track_window: {current_track}
}) => {
jQuery('.playing__song__name').text(current_track.name);
jQuery('.playing__song__artist').text(current_track.artists[0].name);
jQuery('.playing__art img').attr('src', current_track.album.images[0].url);
//Set active item in list
trackList.find('.track').removeClass('playing');
trackList.find('[data-uri="' + current_track.uri + '"]').addClass('playing');
});
}

});

// Connect to the player!
player.connect();
};


Any guidance would be appreciated.







javascript jquery spotify






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 20 '18 at 7:32









AkshayAkshay

2,00431028




2,00431028













  • I'm currently stuck on the exact same problem for iOS, so interested to hear from anyone if this possible on any of the APIs.

    – Benjamin Lowry
    Nov 20 '18 at 8:06



















  • I'm currently stuck on the exact same problem for iOS, so interested to hear from anyone if this possible on any of the APIs.

    – Benjamin Lowry
    Nov 20 '18 at 8:06

















I'm currently stuck on the exact same problem for iOS, so interested to hear from anyone if this possible on any of the APIs.

– Benjamin Lowry
Nov 20 '18 at 8:06





I'm currently stuck on the exact same problem for iOS, so interested to hear from anyone if this possible on any of the APIs.

– Benjamin Lowry
Nov 20 '18 at 8:06












1 Answer
1






active

oldest

votes


















0














Took a look through and it seems to be a problem with your code and not with the SDK itself.



In the player.addListener('ready') block (which will be called automatically when the player is initialised), you have a line, if (typeof search_artist !== "undefined") and another checking if it's undefined. I can't know exactly what's happening without seeing the code where search_artist is defined, but both paths eventually call https://api.spotify.com/v1/me/player/play, resulting in the play you're hearing.



If you want play to happen on click of a button, you should make a separate function for it instead of calling it in a callback.






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53388190%2fdisable-autoplay-on-spotify-sdk%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    Took a look through and it seems to be a problem with your code and not with the SDK itself.



    In the player.addListener('ready') block (which will be called automatically when the player is initialised), you have a line, if (typeof search_artist !== "undefined") and another checking if it's undefined. I can't know exactly what's happening without seeing the code where search_artist is defined, but both paths eventually call https://api.spotify.com/v1/me/player/play, resulting in the play you're hearing.



    If you want play to happen on click of a button, you should make a separate function for it instead of calling it in a callback.






    share|improve this answer




























      0














      Took a look through and it seems to be a problem with your code and not with the SDK itself.



      In the player.addListener('ready') block (which will be called automatically when the player is initialised), you have a line, if (typeof search_artist !== "undefined") and another checking if it's undefined. I can't know exactly what's happening without seeing the code where search_artist is defined, but both paths eventually call https://api.spotify.com/v1/me/player/play, resulting in the play you're hearing.



      If you want play to happen on click of a button, you should make a separate function for it instead of calling it in a callback.






      share|improve this answer


























        0












        0








        0







        Took a look through and it seems to be a problem with your code and not with the SDK itself.



        In the player.addListener('ready') block (which will be called automatically when the player is initialised), you have a line, if (typeof search_artist !== "undefined") and another checking if it's undefined. I can't know exactly what's happening without seeing the code where search_artist is defined, but both paths eventually call https://api.spotify.com/v1/me/player/play, resulting in the play you're hearing.



        If you want play to happen on click of a button, you should make a separate function for it instead of calling it in a callback.






        share|improve this answer













        Took a look through and it seems to be a problem with your code and not with the SDK itself.



        In the player.addListener('ready') block (which will be called automatically when the player is initialised), you have a line, if (typeof search_artist !== "undefined") and another checking if it's undefined. I can't know exactly what's happening without seeing the code where search_artist is defined, but both paths eventually call https://api.spotify.com/v1/me/player/play, resulting in the play you're hearing.



        If you want play to happen on click of a button, you should make a separate function for it instead of calling it in a callback.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 21 '18 at 11:09









        arirawrarirawr

        764618




        764618
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53388190%2fdisable-autoplay-on-spotify-sdk%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            How to pass form data using jquery Ajax to insert data in database?

            National Museum of Racing and Hall of Fame

            Guess what letter conforming each word