Go to spotify dashboard for developers, create an app, take the clientId and place it inside spotify.js file. And then inside the spotify dashboard in edit settings, set the redirect url to match the url your app. How to call the Spotify Public API. First step, head over to the Spotify Public API package page! Next, pick the endpoint you’d like to call. Finally, fill in the parameters and click “Test Function.” Bam! You’ve just called the Spotify API. Some Spotify API endpoints require a Spotify ID for a certain artist. The only issue I have with Spotify API (web playback sdk) is the browser support. I wanted to use it to make a side project but quickly stopped when I realized that it does not support mobile browsers, which is how most people will visit your site. My react app keep refresh url I can't get the token from spotify. It pass me to Spotify's login page and after I login it takes me back to redirecturl which.
In this guide, I'll be demonstrating how to use the Spotify Web Playback API and how to connect it up with a React app.
The Spotify for Developers teamrecently released a beta version of their new web playbackAPI,and I’ve been having a play around with it over the Christmas week. It’s beena lot of fun, and small bugs aside, surprisingly straightforward to workwith.
This project will be focusing purely on getting the API working, so we won’tbe focusing on styling or anything beyond a basic player with controls and a“now playing” display. I’ve hosted the finished code on Glitch—you can findthe link below—where you’re free to edit remix your own copy to your heart’scontent.
This guide assumes that you have some knowledge of Javacript, the browserdevelopment console, React and how APIs work. If you want to learn aboutthese topics, there’s a few resources online I really recommend:
Javascript
React
The first step is to create your project. If you’re doing this locally, Irecommend using the
create-react-app to get started (learn morehere).Otherwise, if you’re following along using Glitch, you can simply remix thisexample React app andyou’re good to go (follow the instructions in the README file though!)
We’ll then start editing the app so that we can store all the informationthat we need:
So, let’s open
src/App.js , and set the state of the App component, settingthese default values:
We’ll also edit the
render() method so that we can display a text box and abutton for the user to enter their Spotify access token.
We then need to update the page to show the form only if the user isn’tlogged into Spotify. We can do this by checking for the
loggedIn statevariable.
On the “logged in” screen, we’ll also display the currently playing track.
I also went to the courtesy of printing out the error value if it gets set,which should hopefully make fixing problems a lot easier further down theline.
You may have noticed that we referenced a new method for the App component,
handleLogin() , which is called when the user clicks on the “Go” button. Fornow, this just updates the state to set loggedIn to true.
The next step is to connect this up to the Spotify API. If you visit theAPI’s quick startpage,under the “Installing the SDK” section, there’s a
<script> tag in the codewhich we’ll use. Paste this into the public/index.html file, and add thislittle script tag too:
The first script tag loads the playback SDK into the browser window. Thesecond one assigns a window variable, called
Spotify , to the globalSpotify variable, inside the window.onSpotifyWebPlaybackSDKReady method.This method is called by the javascript file we just linked when it hasfinished loading, so we know by this point, we can happily use the Spotify variable without any trouble. Spotify stations app for pc.
Setting
window.Spotify may seem a little odd. The reason we do this isbecause React runs on its own copy of the web page’s HTML (for performancereasons, mostly). So it isn’t actually able to see the global Spotify variable! Therefore, we add it to the window object as this can be accesedby React.
Now, if we go back to
src/App.js , we can now create a method to check for thisvariable, and if it exists, to create the Player object—this is what we’lluse to send/receive most data to and from Spotify.
This example works pretty much identically to how thedocumentationrecommends setting things up, but instead of using a constant OAuth token,we’re taking it from our app component’s state, and instead of creating aglobal variable called
player , we just add player as one of the app’sclass variables. This means that we can access it from any of the other classmethods.
Finally, after adding our event handlers (we’ll come onto that shortly) we canthen connect to the player!
One more thing we need to do is to run the
checkForPlayer() method repeatedlyuntil the SDK is ready. For this, we’ll use setInterval to run the methodrepeatedly. Add a new variable for this interval in the constructor, so that wecan cancel the interval later on:
And then we’ll create the interval inside our button click handler.
This will now run the player checking method every second (1000 ms). Of course,once it is created, we need to destroy the interval. So in the
checkForPlayer() , we need to add this:
Handling Events
Now is a good time to set up our event handlers, so we can update our appwhenever something is received from the API. Let’s create another class method,call
createEventHandlers() :
For now, we’ll just print out all information to the developer console.Notice also, that if there’s an authentication error, we set the
loggedIn state variable to false. This will take us back to the login page so that wecan log in again with a new token. This is because we’ll most likely get thiserror if the token is incorrect, or if it has expired (these tokens will onlylast an hour).
Oh, and remember to uncomment the call to
createEventHandlers() in thecheckForPlayer() method!
Now, let’s give this a try. Go to the Spotify documentationpage,and click the button to “get your web playback SDK access token”. Sign inwith your Spotify account and you’ll get your access token:
Now go to your app, and press F12 (or equivalent) to show the developerconsole. Pop the token you just received into the text box and press go.Hopefully you will then see your success message appear!
Now, if you open a Spotify app on any of your devices and start playing somemusic, you should be able to click on the “devices” menu, and see your appthere. Give it a click and you should then be hearing the music come fromyour browser!
You’ll also get some interesting information in the console.
This is the Spotify player’s “state”, which shows information like thecurrent track, tracks coming up, current volume, whether shuffle and repeatmodes are on, and more. We’ll now use this to set our app component’s statevariables.
Twitch royalty free music spotify. You can find out more about the player state object and the information youcan get out of ithere.
We need to handle this player state object to update our app’s own state. Todo this, we’ll create a new method called
onStateChanged() :
This is quite self-explanatory in that it takes the player state object wejust received, and picks out the bits of information we’re interested in,before calling
setState() to update the app component’s state. One thing tonote is that, rather than providing the track artists’ names as a string, wereceive a list of “artist objects”. So a little bit of functional javascriptformats this into a string for us to print out.
Spotify React App Free
Then, we’ll need to update the
player_state_changed event handler so thatwe call our new method:
Open spotify web player. Now, if you log in again with your token, and switch your player to your appusing another Spotify app, you should now be able to see information aboutthe currently playing song!
What’s the use of a music player if we can’t control the music? The next stepfor us to is to create play, previous and next buttons. Let’s update the nowplaying section, inside the
render method:
We’ve added three new buttons to control the player, with the label of theplay/pause button changing depending on if the music is playing or not.
Let’s now wire these buttons up to methods so that they actually do something!We’ll create a new method for each button:
And we also need to update our actual buttons to use these new methods:
Now if you log in and get some music going, these buttons should now allwork! There’s a lot more to the Spotify Web Playback API than just this, so Idefinitely recommend that you check out thedocumentationto find out about all the information you can get about the player’s state,as well as the commands you can send to it. As well as this, there is alsothe existing (and also very good) Web API that allows you to get and set moreplayer settings than you’re able to with the playback API. The best bit isthat the access token you use for the Playback API will work with the Web APItoo, so you’ll only need to get the token once. Spotify also provides a fullOAuth flow, so if you connect your app with a server, you can let users login straight to Spotify and not have to worry about copying tokens around!
Spotify App React Native
So one thing that you may have found annoying was having to go into one ofyour Spotify apps to select the web player to hear music. The good news isthat you can do this through the Spotify Web API! Since it’s still in beta,it sometimes doesn’t work because of a known bug (it’s being worked on), butfor the most part works well. The API endpoint we’ll be using is the
/v1/me/player endpoint.
Let’s make a new method in our app to handle this. We’re using the device ID wereceived when we first connected the player, which is a unique identifier forthe web app:
The
play variable we sent to the API endpoint is set to true here so that,as documented on Spotify’s website, the music will start playing regardlessof whether it was paused by the user on another device beforehand.
Spotify App Download For Pc
The final step is to call this new method when our player connects:
There’s a small issue here—the
transferPlayBackHere() method grabs thedevice ID from the app component’s state. However, the setState method doesnot instantly update the app’s state. However, since it returns a Promise, wecan just make the function asynchronous by adding the async keyword beforethe function declaration (async data => {} ), and then adding the await keyword before the setState() call. We can then add thetransferPlaybackHere() call, safe in the knowledge that the device IDvariable will be set!
And now, if you’re listening to Spotify on any device and log into the webapp, the music should automatically switch over to the web app! The maincaveat here is that Spotify will only let you listen on one device peraccount at a time. The advantage of this though is that you can control anydevice’s playback from the other devices. So essentially, you could use theWeb API to build a remote controller for your media center if you wanted. I’mcurrently working on building a website where you can join rooms with otherpeople and listen to a collaborative playlist at the same time, for example.I’ll release the code and a demo as soon as I have a working versionavailable
There’s a lot of possible things you could do to take your new app further. Here’s some ideas:
Spotify Reactivate Account
Hopefully this guide helped you to get started building awesome apps withReact and the Spotify Web Playback API. If you have any problems, feedback,praise or criticism, please do contact me in one of a few ways:
Install Spotify App
Spotify React App Games
Also, a massive thank you to the Spotify for Developers team. I haven’t beenthis excited an API in quite a long time, and as a big music fan, I can’twait to see what kinds of things I end up building on this platform!
Comments are closed.
|
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |