Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use SoundCloud API in JavaScript SDK

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article focuses on "how to use SoundCloud API in JavaScript SDK". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn how to use SoundCloud API in JavaScript SDK.

Getting started Guid

Promises introduction link address: http://www.oschina.net/translate/what-is-the-point-of-promises?print

Understanding the concepts and working methods of HTTP and API will help you to learn this tutorial. If you want to know more about API, I recommend you take a look at: An Introduction to APIs (an introduction to API. Link address: https://zapier.com/learn/apis/). Knowing a little bit about asynchronous JavaScript,promises and callback functions is also helpful for you to learn this tutorial. JQuery is used in our code examples in this article, so if you know the basics of jQuery, it will be less painful for you to read the code examples in this article.

To start querying SoundClound API using JavaScript, we need to download the JavaScript SDK provided by SoundClound. As mentioned at the beginning of the article, there are two different versions of SDK available.

Which version of SDK do you use?

The main difference between the two versions of SDK is the way they return data when an asynchronous request is generated and sent to SoundClound API. The * version of SDK returns a Promise, while the other version of SDK needs to return a callback function as an argument.

I noticed that with the SDK version of the document, there seems to be a problem in that version of the SDK user login interface, which is that the pop-up login window does not close automatically.

Therefore, for the sake of simplicity and because the older version of SDK is more stable, we will use the old version of SDK throughout this tutorial in the article examples. This version of SDK will need to return a callback function for the client's asynchronous request.

Use SoundCloud API

Set up a basic HTML document

We create a basic HTML page that is used as our home page. We include the address of SDK in the attribute src of the tag on this page, so we can use the function of SDK.

Include SDK-Using SoundCloud API

Note: the SDK address we include in the src of the tag on the HTML page is the server address of SoundCloud. You can also download the SDK and quote it like this:

You can use the following steps to test whether SoundCloud's SDK is loaded correctly on your web page:

Open this page in a browser (Google's Chrome browser is recommended).

Open the developer console in the browser (the shortcut key to open the developer console in Google Chrome browser is Ctrl+Shift+J).

Type SC in the developer console, and then press Enter. SC is a JavaScript object created by the SDK that we just included in the HTML page.

If an unknown error occurs, the SDK for SoundCloud is not loaded correctly. Try to refresh it and make sure that the path to your SDK file (that is, sdk.js file) is correct.

Register for a SoundCloud App

To sign up for a SoundCloud app, all you need to do is have a SoundCloud account. If you don't already have a SoundClound account, create one. By registering an app,SoundCloud server, we can validate our request so that it is not possible for others to send a request on our behalf.

Note: if we are not going to use SoundClound user login in our own website, we can skip this step. This will be explained in the following section.

Open the SoundClound app page. All the app that we have created will be listed on this page. Make sure you log in to your SoundCloud account. Note: you do not need to create a separate account for this purpose. You can use the same account for your personal purposes.

Click the register a new application button.

Give your app a name and click the check box to accept the developer policy terms of SoundCloud.

Click the big "register" button to complete the registration of app.

After we have successfully registered, the registration page will jump directly to the app settings page we just created. On the app settings page, we will see our app client ID, which will be used to verify the request that authorizes us. We can close the page and start callback fields now. We will use this client-side ID later.

Initialize the client

By "initializing the client", that means that we prepare the client to exchange data between it and SoundCloud API. We can initialize the client in the basic HTML document we created earlier, or in an internal js file.

The JavaScript syntax does this:

SC.initialize ({

Client_id: "CLIENT_ID"

Redirect_uri: "CALLBACK_URL"

});

(see the original text for the code)

Let's look at it in sections:

The CLIENT_ID in the above code will be provided to us when we register for app.

The CALLBACK_URL in the above code is the URL of callback.html, which is the name of a HTML file after the user logs in. We will create it soon.

After initialization is complete, we are now ready to query SoundCloud API. Let's look at some examples that we can do before that.

Example

If we open the browser's console and type "SC." then the methods related to the SC object will be listed. One of the methods is SC.get (uri,callback), which is used to generate a GET request to SoundCloud API.

Get a tracking list

To get a random list of traces, we can use the SC.get () method, like this:

SC.get ("/ tracks", function (response) {

For (var I = 0; I

< response.length; i++) { $("ul").append("" + response[i].title + ""); } });

(see the original text for the code)

What is the above code for? it is used to query the / tracks endpoint and return a callback function after querying the endpoint. The response data is stored in the callback response parameter, which is an array of JavaScript objects with many attributes, one of which is the title property. We can write console.log (response [0]) in the code to output * response data in the console log without having to loop through all the objects and their corresponding properties. Then we will know which attributes we can use.

Note: in this code example, we did not specify a callback URL at initialization time. This is because it doesn't matter whether we specify it or not. Our code will be executed anyway. But once we have implemented the user login function, this is necessary and important, because when you specify a callback URL, it is impossible for others to use our Client ID.

Embed a piece of tracking code

The SC object provides other methods: SC.oEmbed (url,options,callback). This method embeds the SoundCloud player into our website and allows us to play the track of our choice.

SC.oEmbed ('https://soundcloud.com/username/complete-url-to-the-track', {maxheight: 200, auto_play: false}, function (res) {$("# player") .html (res.html);})

Let's look at it in sections:

First of all, in the * * parameters of this method, we give a complete tracking URL that we want to play.

The second parameter of this method is optional, in which we can set some options for the player. If you want to learn more, click the following link: https://developers.soundcloud.com/docs/api/reference#oembed

The third argument is a callback function in which we replace the contents of an element in our page (id is player) with the HTML code of the player (res.html).

This tracking path can be used to embed a song or music in a website.

Implement user login

In order to implement the user login function, we need to have a callback URL to verify authorization. This is a requirement of the OAuth agreement. If you want to know about the OAuth protocol, here is a simple explanation of the OAuth protocol: OAuth 2 Simplified (link address: https://aaronparecki.com/2012/07/29/2/oauth3-simplified). So let's add a callback URL called "callback.html" to the app setting, which we will create next.

Introduction to OAuth Protocol Link address: http://menglimengwai.iteye.com/blog/496250

Create a callback page

After a user logs in, the pop-up window is redirected to the file. In our example, we define the file as "callback.html" and save it in the same directory as our home page (index.html). This file is the file we need to give in the callback field in our app settings.

The code we need to use in the callback file is provided in the development documentation. However, the development documentation is a bit out of date, so we need to adjust slightly to meet the current development needs standards.

You can adjust its notification and design according to your personal preferences, but for now, let's make it as simple as possible:

Connect with SoundCloud This popup should automatically close in a few seconds _ document.onload = function () {window.opener.setTimeout (window.opener.SC.connectCallback, 1);}

User login

SC.connect (callback) is the way to implement the user login function. It reminds users to log in to their SoundCloud account by opening a pop-up window. The basic usage is as follows:

SC.connect (function () {console.log ("User has logged in");})

The following is a more interesting example:

SC.connect (function () {SC.get ("/ me", function (response) {console.log ("Welcome" + response.username);});})

Let's look at it in sections:

After the user has finished logging in, the user login page will be redirected to the callback.html page we created earlier.

Then as we finish reading the code in callback.html, the pop-up window closes automatically.

After that, our callback function will get a callback, which is obtained through a GET request to the "/ me" endpoint in the SC.get () method.

When the GET request is completed, the callback function of the above code is executed, and a welcome login message is printed on the console.

Note: the request "/ me" returns the data of the current login user. Therefore, requesting the URL before the user logs in will result in an error message.

Processing user data

Once the user has logged in, there are many things we can do. To demonstrate some functionality, I created a demo site on GitHub. You can click here to view the source code: https://github.com/sitepoint-editors/SC_API, and click here to see how it works: http://mustagheesbutt.github.io/SC_API/.

Let's take a look at these two documents. In index.html, there are four important div elements that will fill up the user's data after the user has logged in:

Welcome

Your Tracks: Your Playlists:

The second most important file is script.js: all miracles happen in this file. We are familiar with most of the code, but let's take a quick look:

/ / Initialization of SDK SC.initialize ({client_id: "21832d295e3463208d2ed0371ae08791", redirect_uri: "http://mustagheesbutt.github.io/SC_API/callback.html"})

First initialize our app. Notice that this time we specified our callback.html page with redirect_uri. This URL or URI must be consistent with what we specified in the app setting.

/ / Login handler var user_perma; $("# login") .click (function () {SC.connect (function () {SC.get ("/ me", function (me) {user_perma = me.permalink; setUI (me.username, me.avatar_url, me.description);}) If (SC.isConnected) {$("header, main") .addClass ("loggedIn");} getTracks (); getPlaylists ();})

Then we add a click event handle to the button labeled id as login. When the button is clicked, the SC.connect (callback) code will be executed in the click event code, and after the code is executed, a window will pop up to prompt the user to log in.

When the user logs in, the pop-up window closes. Then the callback function in SC.connect () executes. In the callback function, we initiate a GET request to the "/ me" endpoint, while the "/ me" endpoint returns the current login user object. In the GET request callback we just initiated, we stored the user's * * link in the variable user_perma, which is defined in the global norm, so we can use it later.

The functions of the setUI () method, getTracks () method, and getPlaylists () method are to set the UI, list the user's tracking records, and list each user's playlist, respectively. These functions are already defined in the same file.

/ / find something to play function play (uri) {url = "http://soundcloud.com/" + user_perma +" / "+ uri; SC.oEmbed (url, {maxheight: 200}, function (resp) {$(" # player ") .html (resp.html);});}

/ use the 'play ()' function to play when a playtrack or playlist is checked

$("ul") .on ("click", function (e) {var title = e.target [XSS _ clean]; if (tracks.hasOwnProperty (title)) {play (trackstitle]);} else if (playlists.hasOwnProperty (title)) {play ("sets/" + playlists [title]);}})

When any trace path or playlist name is clicked, the play () method is executed, which embeds an audio player in our page through the SC.oEmbed () method for the clicked tracking path or playlist name.

We can do a lot of things through the code, such as getting the user type or updating the user's information, getting the user's profile picture, and then running the code to see who the user is and what their hobbies are in the information returned by the SoundCloud server.

At this point, I believe you have a deeper understanding of "how to use SoundCloud API in JavaScript SDK". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report