SoundCloud for Developers

Discover, connect and build

API Wrappers

SoundCloud provides an official JavaScript SDK. All other SDKs (Ruby, Python) are maintained by third-party developers.

JavaScript SDK

The JavaScript SDK integrates SoundCloud into websites and web applications.

In this section:

Basic Use

Add the SDK script to your HTML and initialize the client with your client_id. Include redirect_uri if you need authentication:

<script src="https://connect.soundcloud.com/sdk/sdk-3.3.2.js"></script>
<script>
  SC.initialize({
    client_id: 'YOUR_CLIENT_ID',
    redirect_uri: 'https://example.com/callback'
  });
</script>

The SDK is also available via NPM: npm install soundcloud.

var SC = require('soundcloud');

SC.initialize({
  client_id: 'YOUR_CLIENT_ID',
  redirect_uri: 'https://example.com/callback'
});

Retrieving a user's latest track:

SC.get('/users/183/tracks').then(function(tracks){
  alert('Latest track: ' + tracks[0].title);
});

The JavaScript SDK is open source and available on Github. For example applications, see the examples on this page.

Authentication

Host a callback.html file on your server and set it as the redirect_uri in your app settings and when initializing the SDK. The callback.html file contains:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Connect with SoundCloud</title>
  </head>
  <body onload="window.setTimeout(window.opener.SC.connectCallback, 1)">
    <b style="text-align: center;">This popup should automatically close in a few seconds</b>
  </body>
</html>

Initiate the connect flow by calling SC.connect(). Once authenticated, your app can use SC.post, SC.put, and SC.delete to create comments, like tracks, or update user profiles. Following a user after connecting:

SC.initialize({
  client_id: 'YOUR_CLIENT_ID',
  redirect_uri: 'https://example.com/callback'
});

SC.connect().then(function(){
  return SC.put('/me/followings/183');
}).then(function(user){
  alert('You are now following ' + user.username);
}).catch(function(error){
  alert('Error: ' + error.message);
});

Relevant methods: SC.connect, SC.post, SC.put, SC.delete

API

The SDK provides access to all HTTP endpoints through SC.get, SC.post, SC.put, and SC.delete.

For available endpoints, see the API Reference.

SC.put('/me', {
  user: { description: 'I am using the SoundCloud API!' }
}).then(function(){
  return SC.get('/me');
}).then(function(me){
  console.log(me.description);
}).catch(function(error){
  alert('Error: ' + error.message);
});

Streaming

Track streaming uses the same player as soundcloud.com.

SC.stream('/tracks/293').then(function(player){
  player.play();
});

The player provides methods such as play(), seek(), pause(), and setVolume() to control playback.

Relevant methods: SC.stream

Recording

The SDK uses getUserMedia, Web Workers, and the Web Audio API for recording. Verify browser support (1, 2, 3) before recording. Recording 5 seconds and playing it back:

var recorder = new SC.Recorder();
recorder.start();

setTimeout(function(){
  recorder.stop();
  recorder.play();
}, 5000);

The SDK also supports recording from an arbitrary AudioNode by passing it to the Recorder's constructor. See the documentation and examples for details.

Relevant methods: SC.Recorder

Uploading

Upload recordings and files using SC.upload. Requires browser support for FormData (all modern browsers and IE10+, 1).

SC.upload({
  file: theBlob, // a Blob of your WAV, MP3...
  title: 'This is my sound'
});

SC.upload returns the original request, enabling progress tracking:

var upload = SC.upload({
  file: aBigBlob, // a Blob of your WAV, MP3...
  title: 'This upload took quite some while'
});

upload.request.addEventListener('progress', function(e){
  console.log('progress: ', (e.loaded / e.total) * 100, '%');
});

upload.then(function(track){
  alert('Upload is done! Check your sound at ' + track.permalink_url);
});

Relevant methods: SC.upload

Embedding

SC.oEmbed wraps the SoundCloud oEmbed endpoint.

It takes the URL to embed as an argument and an optional options object. The element property replaces an HTML element with the widget. All options properties are passed as parameters to the oEmbed endpoint (maxwidth, maxheight, auto_play, etc.). See the oEmbed documentation for details.

SC.oEmbed('https://soundcloud.com/forss/flickermood', {
  auto_play: true
}).then(function(embed){
  console.log('oEmbed response: ', embed);
});

Or:

<div id="putTheWidgetHere"></div>
<script type="text/javascript">
  SC.oEmbed('https://soundcloud.com/forss/sets/soulhack', {
    element: document.getElementById('putTheWidgetHere')
  });
</script>

Relevant methods: SC.oEmbed

Examples

For SDK usage examples, see the API Guide.

A combined example application using several SDK methods is available on Github. It records from a user's microphone and uploads the result with webcam-generated artwork.

Promises

The SDK uses Promises for most methods. Promises enable composable API calls with structured error handling.

Chain promises with then() and handle errors with catch(). For an introduction, see html5rocks.com/en/tutorials/es6/promises.

The SDK uses es6-promise to shim the Promise object where unavailable. The library is exposed via SC.Promise for methods like Promise.all and Promise.race.

Relevant methods: SC.Promise

API Documentation

SC.initialize(options)

Initializes the SDK.

Parameters:

  • options (Object):
    • client_id: Your application's client id
    • redirect_uri (optional): Required only for user authentication
    • oauth_token (optional): Reuse an existing access token

SC.connect(options)

Initiates the OAuth2 connect flow.

Parameters:

  • options (Object, optional):
    • client_id: Override the previously set client id
    • redirect_uri: The redirect URI defined in your app settings
    • scope: Additional OAuth2 scopes (default: "*")

Returns: A promise that resolves with a session data object

SC.get(path, [params])

Executes a GET request.

Parameters:

  • path (String): Path to the requested resource, e.g. /users/183
  • params (Object, optional): Additional parameters for the request

Returns: A promise that resolves with the requested resource

SC.post(path, [params])

Executes a POST request.

Parameters:

  • path (String): Path to the requested resource, e.g. /me/followings
  • params (Object / FormData, optional): Additional parameters for the request body

Returns: A promise that resolves with the requested resource

SC.put(path, [params])

Executes a PUT request.

Parameters:

  • path (String): Path to the requested resource, e.g. /me
  • params (Object / FormData, optional): Additional parameters for the request body

Returns: A promise that resolves with the requested resource

SC.delete(path)

Executes a DELETE request.

Parameters:

  • path (String): Path to the requested resource

Returns: A promise that resolves when the resource has been deleted

SC.upload(options)

Uploads a file or recording to SoundCloud.

Parameters:

  • options (Object):
    • file (Blob): A Blob of the file or recording (see recorder.getWAV())
    • title (String): Title for the recording
    • progress (Function): Progress callback
    • Accepts all other upload request params such as artwork_data or sharing (see API Reference)

Returns: A promise that resolves when the upload completes. Contains a reference to the original request (see Uploading).

SC.resolve(url)

Resolves a SoundCloud URL to a JSON representation of the resource.

Parameters:

  • url (String): URL to a track, playlist, or user on SoundCloud

Returns: A promise that resolves with a JSON object

SC.oEmbed(url, [params])

Looks up embed code for the passed URL (track, set, or user) using oEmbed.

Parameters:

  • url (String): URL to a track, set, or user on SoundCloud
  • params (Object, optional): Additional oEmbed parameters (see oEmbed docs). Accepts an element property that replaces the HTML element with the widget.

Returns: A promise that resolves with oEmbed info for the resource

SC.stream(trackPath, [secretToken])

Creates a player for the specified stream.

Parameters:

  • trackPath (String): Path of the track to stream, e.g. /tracks/293
  • secretToken (String, optional): Secret token for the track

Returns: A promise that resolves with a player for the track

SC.Recorder(options)

Constructor function returning a Web Audio Recorder instance. Must be called with new.

Parameters:

  • options (Object, optional):
    • context: An AudioContext to reuse
    • source: An AudioNode to record from

recorder.start()

Starts recording from the user's computer or the source passed to the constructor.

Requires Web Audio API, Web Workers, and getUserMedia support.

recorder.stop()

Stops the current recording.

recorder.play()

Plays back the current recording.

Returns: The AudioNode used for playback

recorder.getWAV()

Returns: A promise that resolves with a WAV Blob of the current recording

recorder.getBuffer()

Returns: A promise that resolves with an AudioBuffer of the current recording

recorder.saveAs(filename)

Downloads the recorded WAV to the user's computer.

Parameters:

  • filename (String): The desired filename

recorder.delete()

Stops and deletes the recording.

SC.Promise

The promise prototype used internally by the SDK (es6-promise). Use it to create custom promises or call Promise.all and Promise.race.

Player (methods & events)

Methods

Control the player returned from SC.stream:

  • play(): Starts playback. Returns a Promise that resolves when playback starts; may reject if the browser refuses playback.
  • pause(): Pauses the player
  • seek(time): Seeks to a position in milliseconds. Returns a Promise that resolves on completion; may reject if the seek is not possible.
  • currentTime(): Returns the current position in milliseconds
  • setVolume(volume): Sets volume (0 to 1)
  • getVolume(): Returns the current volume
  • getDuration(): Returns the duration in milliseconds
  • isBuffering(): Returns true while buffering
  • isPlaying(): Returns true while the intended state is playing (flips with play() and pause())
  • isActuallyPlaying(): Returns true while actually playing
  • hasErrored(): Returns true if the player has encountered a fatal error
  • isDead(): Returns true if the player is dead
  • getState(): Returns 'playing', 'paused', 'loading', 'ended', 'error', or 'dead'
  • kill(): Destroys the player. Call when no longer needed.
  • on(event, handler): Subscribes a handler to an event

Events

Subscribe to events using the player's on(event, handler) method:

  • state-change: Audio controller state change. Values: 'playing', 'paused', 'loading', 'ended', 'error', or 'dead'
  • play: play method called
  • play-start: Playback starts for the first time
  • play-resume: Playback starts on subsequent plays
  • play-rejection: Browser rejects a play request
  • pause: Playback paused
  • finish: Sound finished
  • seek: seek method called
  • seeked: Seek completes
  • seek-rejection: Seek rejected
  • geo_blocked: No streams available for the user's territory
  • buffering_start: Buffering starts
  • buffering_end: Buffering stops
  • audio_error: An error occurs
  • time: Playback position updated
  • no_streams: Failed to fetch stream information
  • no_protocol: No supported protocol found
  • no_connection: Failed to connect due to missing transport or request timeout