<cite id="uzm8y"><strike id="uzm8y"></strike></cite>

    1. <var id="uzm8y"><menu id="uzm8y"></menu></var>
    2. <button id="uzm8y"></button>
      ><\/span><\/body<\/span>><\/span>\n<\/span><\/html<\/span>><\/span>\n<\/span><\/pre>\n

      Notice that we have included the SDK in our page directly from SoundCloud’s servers. You can also download the SDK and reference to it like:<\/p>\n

      
      	
      
      
      
      
      
      
      

      亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

      Table of Contents
      Key Takeaways
      Getting Started
      Which Version of the SDK to Use?
      Using the SoundCloud API
      Setup a Basic HTML Document
      Register a SoundCloud App
      Initialize the Client
      Examples
      Getting a List of Tracks
      Embedding a Track
      Implementing User Login
      Create the Callback Page
      Logging the User In
      Playing with the User’s Data
      Summary
      Frequently Asked Questions (FAQs) about Using SoundCloud API with JavaScript SDK
      What are the prerequisites for using the SoundCloud API with JavaScript SDK?
      How do I register an application on SoundCloud to get a client ID?
      How do I initialize the SoundCloud API with my client ID?
      How do I make API requests to SoundCloud?
      How do I handle errors when making API requests?
      How do I play a track using the SoundCloud API?
      How do I pause and resume a track?
      How do I get the details of a track?
      How do I search for tracks?
      How do I get a user’s tracks?
      Home Web Front-end JS Tutorial Using the SoundCloud API with the JavaScript SDK

      Using the SoundCloud API with the JavaScript SDK

      Feb 18, 2025 am 11:20 AM

      Using the SoundCloud API with the JavaScript SDK

      Key Takeaways

      • The SoundCloud API allows developers to access almost any data they need. The API is a collection of URLs that provide access to data from SoundCloud servers, while the SDK (Software Development Kit) is a pre-written library for querying the API.
      • There are two versions of the SDK available. The major difference between them is how they return data when an asynchronous request is made to the API. The latest version returns a Promise, while the other requires a callback function as a parameter.
      • To start querying the SoundCloud API using JavaScript, the JavaScript SDK provided by SoundCloud needs to be downloaded. For user-login functionality, the older version of the SDK is recommended as it is more stable.
      • Data from the SoundCloud API can be accessed with a simple GET request. User-specific data can be obtained using the /me endpoint, but only if the user is logged in to the website using their SoundCloud account.
      • Querying an API from the client-side can save developers from the complexities of back-end. The SDK simplifies the process, enabling the creation of more powerful and user-friendly web applications.
      This article was peer reviewed by Jamie Shields and Wern Ancheta. Thanks to all of SitePoint’s peer reviewers for making SitePoint content the best it can be!

      SoundCloud has made available an API which allows developers to get almost any data they want. But its usage can be confusing, especially for beginners, because as of now the SoundCloud API documentation and the examples use different versions of the SDK (Software Development Kit).

      What is the difference between the API and the SDK? Basically, the API is a collection of URLs that provide access to data from the SoundCloud servers, and the SDK is a pre-written library (or client) for querying the API. To learn more see this discussion.

      In this tutorial, we will learn how to access the SoundCloud API and how to simplify the process using the SDK. We will walk though setting up the SDK and then write the JavaScript to get data, play audio and more from SoundCloud.

      Getting Started

      Knowing the concepts and workings of HTTP and APIs will be helpful. If you want to learn more about APIs, I recommend this short course: An Introduction to APIs. A little knowledge of asynchronous JavaScript, promises and callbacks will also help. jQuery is used in our code examples, so knowing the basics won’t hurt.

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

      Which Version of the SDK to Use?

      The major difference between them is how they return data when an asynchronous request is made to the API. The latest version returns a Promise, while the other requires a callback function as a parameter.

      One problem I noticed, is that with the version of SDK used by the documentation, there seems to be an issue with user-login functionality, as the pop-up window doesn’t close automatically.

      So, for simplicity’s sake, and because it is more stable, we will use the old version in the examples throughout this tutorial. This version will require callback functions for asynchronous requests.

      Using the SoundCloud API

      Setup a Basic HTML Document

      We will create a basic HTML page which will serve as our homepage. We will also include the SDK here, so we can make use of its functionality.

      <span><span><!DOCTYPE html></span>
      </span><span><span><span><html</span>></span>
      </span>  <span><span><span><head</span>></span>
      </span>    <span><span><span><title</span>></span>Include SDK - Using SoundCloud API<span><span></title</span>></span>
      </span>    <span><span><span><script</span> src<span>="//connect.soundcloud.com/sdk.js"</span>></span><span><span></script</span>></span>
      </span>  <span><span><span></head</span>></span>
      </span>  <span><span><span><body</span>></span><span><span></body</span>></span>
      </span><span><span><span></html</span>></span>
      </span>

      Notice that we have included the SDK in our page directly from SoundCloud’s servers. You can also download the SDK and reference to it like:

      <span><span><span><script</span> src<span>="sdk.js"</span>></span><span><span></script</span>></span>
      </span>

      To test if the SDK gets loaded in your webpage correctly:

      • Open up the page in a browser (Chrome recommended).
      • Open up Developer Console in the browser (Ctrl Shift J, in Chrome).
      • In the Console, type SC and press enter. SC is a Javascript Object created by the SDK which we just included.

      If an undefined error shows up then it is not loading correctly. Try refreshing and make sure the path to the SDK file (sdk.js) is correct.

      Register a SoundCloud App

      To register a SoundCloud app, all you need is a SoundCloud account. If you don’t have one already, go ahead and create one. By registering an app, SoundCloud servers will be able to verify our request, so no one else can make a request on our behalf.

      Note: We can skip this step, if we are not going to use the user-login feature in our website. It will be explained in the next section.

      • Open the SoundCloud apps page. Here any apps we have already created will be listed. Make sure you are logged in to your SoundCloud account. Note: You do not need to make a separate account for this purpose. You can use the same account which you use for personal purposes.

      • Click on the Register a new application button. Using the SoundCloud API with the JavaScript SDK

      • Give it a name and accept SoundCloud’s Developer Policies by checking the checkbox. Using the SoundCloud API with the JavaScript SDK

      • Click on the big Register button, to complete the app registration.

      After we have successfully registered, we will be redirected to the settings page of our newly created app. There we will find our app’s Client ID, which will be used to authorize our requests. We can leave the website and callback fields for now. We’ll get to that later.

      Initialize the Client

      By “initializing the client”, we mean to make the client ready to exchange data between itself and SoundCloud API. We can do it in our basic HTML document, which we created earlier, or in an external .js file.

      The JavaScript syntax to do so is:

      <span><span><!DOCTYPE html></span>
      </span><span><span><span><html</span>></span>
      </span>  <span><span><span><head</span>></span>
      </span>    <span><span><span><title</span>></span>Include SDK - Using SoundCloud API<span><span></title</span>></span>
      </span>    <span><span><span><script</span> src<span>="//connect.soundcloud.com/sdk.js"</span>></span><span><span></script</span>></span>
      </span>  <span><span><span></head</span>></span>
      </span>  <span><span><span><body</span>></span><span><span></body</span>></span>
      </span><span><span><span></html</span>></span>
      </span>

      Let’s break it down:

      • The CLIENT_ID is provided to us when we register our app.
      • CALLBACK_URL is the URL to callback.html, an HTML file which gets called after the user has logged in. We will create it soon.

      Now, after initialization, we are ready to query the SoundCloud API. Let’s take a look at some examples of what we can do already.

      Examples

      If we open up browser console and type SC., a list of methods associated with the SC object will appear. SC.get(uri, callback) is one of them, which is used for making GET requests to the API.

      Getting a List of Tracks

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

      <span><span><span><script</span> src<span>="sdk.js"</span>></span><span><span></script</span>></span>
      </span>

      See the Pen Listing Tracks by SitePoint (@SitePoint) on CodePen.

      What this does, is that it queries the /tracks endpoint and expects a callback function. The response is stored in the response parameter of callback, which is an array of JavaScript objects with multiple properties, title being one of them. We can console.log(response[0]) instead of looping to see a whole object and its properties. Then we will know which properties we have access to.

      Notice, in this example we have not specified a callback URL during initialization. This is because here it doesn’t matter if we specify it or not. Either way our code will work. But when we will implement user-login functionality, it will matter and will be required so no one else can use our Client ID.

      Embedding a Track

      The SC object offers another method, SC.oEmbed(url, options, callback), which embeds the SoundCloud player in our website and allows us to play a track of our choice.

      <span>SC.initialize({
      </span>  <span>client_id: "CLIENT_ID",
      </span>  <span>redirect_uri: "CALLBACK_URL"
      </span><span>});
      </span>

      See the Pen Embedding a Track by SitePoint (@SitePoint) on CodePen.

      Let’s break it down:

      • First we give it a complete URL of the track we want to play.
      • In the options parameter, we set some options for the player. See more here.
      • In the callback function, we replace the contents of an element (#player) in our page with the HTML code for the player (res.html).

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

      Implementing User Login

      For the implementation of user-login functionality, we need to have a callback URL for authorization purposes. This is a requirement of the OAuth protocol. If you are curious about it, here’s a simplified explanation of : OAuth 2 Simplified. So let’s go ahead and update the app settings to include a callback URL of callback.html, which we are now going to create.

      Create the Callback Page

      After a user has logged in, the pop-up window redirects to this file. In our case, we will name it callback.html and it will reside in the same directory as our home page (index.html). This is the file we need to give in the callback field in our app settings.

      Using the SoundCloud API with the JavaScript SDK

      The code we need to use within the callback file is provided in documentation. However, the documentation is a little outdated, so we’ll modify it slightly to meet modern standards.

      You can modify its message and design as much as you would like to , but for now, we will keep it as simple as possible:

      <span><span><!DOCTYPE html></span>
      </span><span><span><span><html</span>></span>
      </span>  <span><span><span><head</span>></span>
      </span>    <span><span><span><title</span>></span>Include SDK - Using SoundCloud API<span><span></title</span>></span>
      </span>    <span><span><span><script</span> src<span>="//connect.soundcloud.com/sdk.js"</span>></span><span><span></script</span>></span>
      </span>  <span><span><span></head</span>></span>
      </span>  <span><span><span><body</span>></span><span><span></body</span>></span>
      </span><span><span><span></html</span>></span>
      </span>

      Logging the User In

      SC.connect(callback) is the method for implementing the user-login feature. It opens up a pop-up window, prompting the user to login to their SoundCloud account. The basic usage is as below:

      <span><span><span><script</span> src<span>="sdk.js"</span>></span><span><span></script</span>></span>
      </span>

      A slightly more interesting example would be:

      <span>SC.initialize({
      </span>  <span>client_id: "CLIENT_ID",
      </span>  <span>redirect_uri: "CALLBACK_URL"
      </span><span>});
      </span>

      Let’s break it down:

      • After the user has logged in, they will be redirected to callback.html, which we created earlier.
      • Then the pop-up window will automatically close, as we can guess by reading the code in callback.html.
      • After that, our callback function will get called, in which a GET request to /me endpoint is made using SC.get() method.
      • As soon as the GET request completes, its callback function gets executed and a welcome message gets logged to the console.

      Notice that a request to /me will return data about the currently logged in user. Therefore, using it before the user has been logged in will result in an error message.

      Playing with the User’s Data

      Once the user has logged in, there is so much more we can do. To demonstrate some of the power, I have created a demo website on GitHub. You can find the source code here and see it in action here.

      Let’s walk through two of the files. In index.html, the four divs are of importance, as they get filled out with user data after user has logged in:

      <span><span><!DOCTYPE html></span>
      </span><span><span><span><html</span>></span>
      </span>  <span><span><span><head</span>></span>
      </span>    <span><span><span><title</span>></span>Include SDK - Using SoundCloud API<span><span></title</span>></span>
      </span>    <span><span><span><script</span> src<span>="//connect.soundcloud.com/sdk.js"</span>></span><span><span></script</span>></span>
      </span>  <span><span><span></head</span>></span>
      </span>  <span><span><span><body</span>></span><span><span></body</span>></span>
      </span><span><span><span></html</span>></span>
      </span>

      The next most important file is script.js: all of the magic happens here. Most of the code will be familiar to us, but let’s walk through it quickly:

      <span><span><span><script</span> src<span>="sdk.js"</span>></span><span><span></script</span>></span>
      </span>
      • First we initialize our app. Notice, this time we have redirect_uri specified as our callback.html page. This URL or URI should exactly match with the URL we have specified in our app settings.
      <span>SC.initialize({
      </span>  <span>client_id: "CLIENT_ID",
      </span>  <span>redirect_uri: "CALLBACK_URL"
      </span><span>});
      </span>
      • Then we attach a click event handler to the #login button. Which when clicked, will execute SC.connect(callback) which opens a pop-up window prompting user to login.
      • After the user has logged-in, pop-up window closes. Then the callback function of SC.connect() gets executed. Inside the callback function, we make a GET request to the /me endpoint which returns the object of currently logged-in user. In the callback of the GET request we just made, we store the user’s permalink in the variable user_perma, which is defined in global scope, so we can use it later.
      • The functions setUI(), getTracks() and getPlaylists(), set up the UI, list the user’s tracks and list the user’s playlists respectively. These functions are defined in the same file.
      <span>SC.get("/tracks", function(response) {
      </span>  <span>for (var i = 0; i < response.length; i++) {
      </span>    <span>$("ul").append("<li>" + response[i].title + "</li>");
      </span>  <span>}
      </span><span>});
      </span>
      • When any track or playlist name gets clicked, the play() function executes, which embeds an audio player in our page using the SC.oEmbed() method, for that track or playlist .

      There is much more we can do, such as getting or updating the user’s description, getting the user’s avatar, seeing who the user is following and their favourites.

      Summary

      • Use the older version of the SDK, if user-login feature is to be used. It is stable, and data is returned using callback functions.
      • If the user-login feature is not used, the newer version of the SDK can be used. It uses promises to return data.
      • Data from SoundCloud API can be accessed by a simple GET request.
      • User-specific data can be obtained using /me endpoint, but only if the user is logged-in to our website using their SoundCloud account.

      Querying an API from the client-side is a powerful tool as it saves us from the complexities of back-end. The SDK makes our lives a whole lot easier. After learning its basics, we can create even more powerful and user-friendly web applications. See some examples of what’s possible, and check out the official SoundCloud documentation to learn more about the advanced API methods available.

      I’d love to hear from you about what things you’ve built (or are planning to build) with the SoundCloud SDK. Let me know in the comments!

      Frequently Asked Questions (FAQs) about Using SoundCloud API with JavaScript SDK

      What are the prerequisites for using the SoundCloud API with JavaScript SDK?

      To use the SoundCloud API with JavaScript SDK, you need to have a basic understanding of JavaScript and how APIs work. You also need to have a SoundCloud account and a registered application on SoundCloud. The registered application will provide you with a client ID, which is necessary for making API requests.

      How do I register an application on SoundCloud to get a client ID?

      To register an application on SoundCloud, you need to log in to your SoundCloud account and navigate to the ‘Apps’ section. Here, you can create a new application by providing the necessary details such as the application name, description, website, and redirect URI. Once the application is created, you will be provided with a client ID.

      How do I initialize the SoundCloud API with my client ID?

      To initialize the SoundCloud API, you need to use the SC.initialize method and pass in an object with your client ID. Here’s an example:

      SC.initialize({
      client_id: 'YOUR_CLIENT_ID'
      });

      Replace ‘YOUR_CLIENT_ID’ with the client ID of your registered application.

      How do I make API requests to SoundCloud?

      You can make API requests to SoundCloud using the SC.get method. This method takes two parameters: the endpoint and a callback function. The endpoint is the URL of the API resource you want to access, and the callback function is executed when the API response is received.

      How do I handle errors when making API requests?

      When making API requests, errors can be handled using the catch method. This method takes a function as a parameter, which is executed when an error occurs. The error object is passed to this function, allowing you to handle the error appropriately.

      How do I play a track using the SoundCloud API?

      To play a track using the SoundCloud API, you need to use the SC.stream method. This method takes the track’s URI as a parameter and returns a stream object. You can then use the play method on this object to play the track.

      How do I pause and resume a track?

      To pause a track, you can use the pause method on the stream object. To resume the track, you can use the play method again.

      How do I get the details of a track?

      To get the details of a track, you can use the SC.get method and pass the track’s URI as a parameter. The API response will contain the track’s details.

      How do I search for tracks?

      To search for tracks, you can use the SC.get method and pass ‘/tracks’ as the endpoint. You can also pass a query parameter to filter the tracks. For example, to search for tracks with the title ‘My Track’, you can use the following code:

      SC.get('/tracks', { q: 'My Track' }).then(function(tracks) {
      console.log(tracks);
      });

      How do I get a user’s tracks?

      To get a user’s tracks, you can use the SC.get method and pass ‘/users/{user_id}/tracks’ as the endpoint. Replace ‘{user_id}’ with the ID of the user. The API response will contain the user’s tracks.

      The above is the detailed content of Using the SoundCloud API with the JavaScript SDK. For more information, please follow other related articles on the PHP Chinese website!

      Statement of this Website
      The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

      Hot AI Tools

      Undress AI Tool

      Undress AI Tool

      Undress images for free

      Undresser.AI Undress

      Undresser.AI Undress

      AI-powered app for creating realistic nude photos

      AI Clothes Remover

      AI Clothes Remover

      Online AI tool for removing clothes from photos.

      Clothoff.io

      Clothoff.io

      AI clothes remover

      Video Face Swap

      Video Face Swap

      Swap faces in any video effortlessly with our completely free AI face swap tool!

      Hot Tools

      Notepad++7.3.1

      Notepad++7.3.1

      Easy-to-use and free code editor

      SublimeText3 Chinese version

      SublimeText3 Chinese version

      Chinese version, very easy to use

      Zend Studio 13.0.1

      Zend Studio 13.0.1

      Powerful PHP integrated development environment

      Dreamweaver CS6

      Dreamweaver CS6

      Visual web development tools

      SublimeText3 Mac version

      SublimeText3 Mac version

      God-level code editing software (SublimeText3)

      Hot Topics

      PHP Tutorial
      1488
      72
      How to make an HTTP request in Node.js? How to make an HTTP request in Node.js? Jul 13, 2025 am 02:18 AM

      There are three common ways to initiate HTTP requests in Node.js: use built-in modules, axios, and node-fetch. 1. Use the built-in http/https module without dependencies, which is suitable for basic scenarios, but requires manual processing of data stitching and error monitoring, such as using https.get() to obtain data or send POST requests through .write(); 2.axios is a third-party library based on Promise. It has concise syntax and powerful functions, supports async/await, automatic JSON conversion, interceptor, etc. It is recommended to simplify asynchronous request operations; 3.node-fetch provides a style similar to browser fetch, based on Promise and simple syntax

      JavaScript Data Types: Primitive vs Reference JavaScript Data Types: Primitive vs Reference Jul 13, 2025 am 02:43 AM

      JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

      React vs Angular vs Vue: which js framework is best? React vs Angular vs Vue: which js framework is best? Jul 05, 2025 am 02:24 AM

      Which JavaScript framework is the best choice? The answer is to choose the most suitable one according to your needs. 1.React is flexible and free, suitable for medium and large projects that require high customization and team architecture capabilities; 2. Angular provides complete solutions, suitable for enterprise-level applications and long-term maintenance; 3. Vue is easy to use, suitable for small and medium-sized projects or rapid development. In addition, whether there is an existing technology stack, team size, project life cycle and whether SSR is needed are also important factors in choosing a framework. In short, there is no absolutely the best framework, the best choice is the one that suits your needs.

      JavaScript time object, someone builds an eactexe, faster website on Google Chrome, etc. JavaScript time object, someone builds an eactexe, faster website on Google Chrome, etc. Jul 08, 2025 pm 02:27 PM

      Hello, JavaScript developers! Welcome to this week's JavaScript news! This week we will focus on: Oracle's trademark dispute with Deno, new JavaScript time objects are supported by browsers, Google Chrome updates, and some powerful developer tools. Let's get started! Oracle's trademark dispute with Deno Oracle's attempt to register a "JavaScript" trademark has caused controversy. Ryan Dahl, the creator of Node.js and Deno, has filed a petition to cancel the trademark, and he believes that JavaScript is an open standard and should not be used by Oracle

      Handling Promises: Chaining, Error Handling, and Promise Combinators in JavaScript Handling Promises: Chaining, Error Handling, and Promise Combinators in JavaScript Jul 08, 2025 am 02:40 AM

      Promise is the core mechanism for handling asynchronous operations in JavaScript. Understanding chain calls, error handling and combiners is the key to mastering their applications. 1. The chain call returns a new Promise through .then() to realize asynchronous process concatenation. Each .then() receives the previous result and can return a value or a Promise; 2. Error handling should use .catch() to catch exceptions to avoid silent failures, and can return the default value in catch to continue the process; 3. Combinators such as Promise.all() (successfully successful only after all success), Promise.race() (the first completion is returned) and Promise.allSettled() (waiting for all completions)

      What is the cache API and how is it used with Service Workers? What is the cache API and how is it used with Service Workers? Jul 08, 2025 am 02:43 AM

      CacheAPI is a tool provided by the browser to cache network requests, which is often used in conjunction with ServiceWorker to improve website performance and offline experience. 1. It allows developers to manually store resources such as scripts, style sheets, pictures, etc.; 2. It can match cache responses according to requests; 3. It supports deleting specific caches or clearing the entire cache; 4. It can implement cache priority or network priority strategies through ServiceWorker listening to fetch events; 5. It is often used for offline support, speed up repeated access speed, preloading key resources and background update content; 6. When using it, you need to pay attention to cache version control, storage restrictions and the difference from HTTP caching mechanism.

      Leveraging Array.prototype Methods for Data Manipulation in JavaScript Leveraging Array.prototype Methods for Data Manipulation in JavaScript Jul 06, 2025 am 02:36 AM

      JavaScript array built-in methods such as .map(), .filter() and .reduce() can simplify data processing; 1) .map() is used to convert elements one to one to generate new arrays; 2) .filter() is used to filter elements by condition; 3) .reduce() is used to aggregate data as a single value; misuse should be avoided when used, resulting in side effects or performance problems.

      JS roundup: a deep dive into the JavaScript event loop JS roundup: a deep dive into the JavaScript event loop Jul 08, 2025 am 02:24 AM

      JavaScript's event loop manages asynchronous operations by coordinating call stacks, WebAPIs, and task queues. 1. The call stack executes synchronous code, and when encountering asynchronous tasks, it is handed over to WebAPI for processing; 2. After the WebAPI completes the task in the background, it puts the callback into the corresponding queue (macro task or micro task); 3. The event loop checks whether the call stack is empty. If it is empty, the callback is taken out from the queue and pushed into the call stack for execution; 4. Micro tasks (such as Promise.then) take precedence over macro tasks (such as setTimeout); 5. Understanding the event loop helps to avoid blocking the main thread and optimize the code execution order.

      See all articles