API Wrappers
The SDKs will make it easier to access the SoundCloud API on your framework of choice. We officially provide and support only JavaScript. All other SDKs (Ruby, Python) are supported by third-party developers.
We welcome contributions to the open source projects so imagine how happy we'd be if you submit an SDK of your own for any additional language.
JavaScript SDK
The JavaScript SDK lets you easily integrate SoundCloud into your website or webapp.
In this section:
Basic Use
To start using the SDK just add this script to your HTML and initialize the client with your own client_id
and optionally your redirect_uri
in case you want to use 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>
You can also install the SDK via NPM now: npm install soundcloud
.
var SC = require('soundcloud');
SC.initialize({
client_id: 'YOUR_CLIENT_ID',
redirect_uri: 'https://example.com/callback'
});
Once that's done you are all set and ready to use the SoundCloud API. For example getting a user's latest track:
SC.get('/user/183/tracks').then(function(tracks){
alert('Latest track: ' + tracks[0].title);
});
The JavaScript SDK is open source and can be found on Github. If you are looking for example applications, have a look at the examples on this page.
Authentication
To use the authentication you have to host a callback.html
file on your server and set it as the redirect_uri
in your app settings and when initializing the SDK. This callback.html
file needs to contain just a few lines:
<!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>
You initiate the connect flow by calling SC.connect()
. Once your users are authenticated and authorized, your app is allowed to use the HTTP methods SC.post, SC.put and SC.delete to create comments, liking a track or updating user profiles. The following example shows how to follow a user, after connecting the current user:
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 easy access to all HTTP endpoints through the SC.get, SC.post, SC.put and SC.delete methods.
For a list of available endpoints, check 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
Streaming tracks from the SDK is powered by the same player that is also used on soundcloud.com to ensure the best playback experience.
SC.stream('/tracks/293').then(function(player){
player.play();
});
The player has all basic methods to control the playback flow like play()
, seek()
, pause()
, setVolume()
, etc.
Relevant methods: SC.stream
Recording
The SDK uses getUserMedia, Web Workers and the Web Audio API to record from a user's computer, so make sure to check if the user's browser supports all of it (1, 2, 3) before you start recording. This example will record 5 seconds and play it back right away:
var recorder = new SC.Recorder();
recorder.start();
setTimeout(function(){
recorder.stop();
recorder.play();
}, 5000);
In addition to recording from the user's computer, the SDK also supports recording from an arbitrary AudioNode by passing it to the Recorder's constructor. Check out the documentation and the examples for more information.
Relevant methods: SC.Recorder
Uploading
You can upload recordings and files using the SDK's SC.upload
method. This method requires the user's browser to support FormData (supported in all modern browsers and IE10+, 1).
SC.upload({
file: theBlob, // a Blob of your WAV, MP3...
title: 'This is my sound'
});
Uploads can take a while and it makes sense to inform the user about the progress. For this reason, SC.upload
returns the original request as well so that you can calculate the progress yourself.
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
The SC.oEmbed
function is a wrapper for the SoundCloud oEmbed endpoint.
It takes the URL you want to embed as an argument, and an optional options object that can contain an element that should be replaced by the embed code. All of the options
object's properties will be passed as parameters to the oEmbed endpoint. For example maxwidth
, maxheight
, or auto_play
. The options are described in detail in the oEmbed documentation.
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
If you want to check out more SDK usage examples, head over to the API Guide. It shows how to use API methods in all available SDKs.
An example of an application that is using a combination of several SDK methods can be found on Github. It records a user's microphone and uploads it together with an artwork that is generated from the user's webcam. (no Flash required!)
Promises
The SDK uses Promises for most of its methods. They provide a way to easily compose API calls and offer a sane way to handle the various errors that can occur.
Promises can be chained by using their then()
method and errors can be handled in a catch()
handler. If you are new to Promises, check out this introductory blog artice on HTML5 rocks: html5rocks.com/en/tutorials/es6/promises.
In order to conform with the ES6 standard, the SDK uses es6-promise which shims the Promise
object on systems where it is not available. We also expose the library via SC.Promise, so that you can use methods like Promise.all
or Promise.race
even if your user's browser is not supporting Promises yet.
Relevant methods: SC.Promise
API Documentation
SC.initialize(options)
Initializes the SDK.
Parameters:
-
options (Object)
:client_id
: You application's client idredirect_uri
(optional): Only needed if you want to authenticate usersoauth_token
(optional): If you want to reuse an access token
SC.connect(options)
Initiate the OAuth2 connect flow.
Parameters:
-
options (Object, optional)
:client_id
: override the before set client id.redirect_uri
: the redirect URI as defined in your app settings.scope
: additional OAuth2 scopes (default: "*")
Returns: A promise that will resolve with a session data object
SC.get(path, [params])
Execute a GET request.
Parameters:
path (String)
: the path to the requested resource e.g. '/users/183'params (Object, optional)
: an object of additional parameters to pass in the request.
Returns: A promise that will resolve with the requested resource
SC.post(path, [params])
Execute a POST request.
Parameters:
path (String)
: the path to the requested resource e.g. '/me/followings'params (Object / FormData, optional)
: an object of additional parameters to pass in the request body.
Returns: A promise that will resolve with the requested resource
SC.put(path, [params])
Execute a PUT request.
Parameters:
path (String)
: the path to the requested resource e.g. '/me'params (Object / FormData, optional)
: an object of additional parameters to pass in the request body.
Returns: A promise that will resolve with the requested resource
SC.delete(path)
Execute a DELETE request.
Parameters:
path (String)
: the path to the requested resource
Returns: A promise that will resolve when the resource has been deleted
SC.upload(options)
Uploads a file or a recording to SoundCloud
Parameters:
-
options (Object)
:file (Blob)
: a Blob of the file or the recording (see recorder.getWAV()).title (String)
: a title for the recording.progress (Function)
: a progress callback.- It also accepts all other params for upload requests, such as
artwork_data
orsharing
(see API Reference for a full list).
Returns: A promise that will resolve when the resource has been uploaded. It also contains a reference to the original request (see Uploading)
SC.resolve(url)
Resolves a SoundCloud URL to a JSON representation of the requested resource
Parameters:
url (String)
: a URL to a track, playlist or user on SoundCloud.
Returns: A promise that will resolve with a JSON object
SC.oEmbed(url, [params])
Will lookup the embed code for the passed URL (track, set or user) using oEmbed
Parameters:
url (String)
: a URL to a track, set or user on SoundCloud.params (Object, optional)
: additional parameters for oEmbed. See oEmbed docs. In addition to that, it accepts anelement
property that will replace the HTML element with the widget.
Returns: A promise that will resolve with the oEmbed info for the resource
SC.stream(trackPath, [secretToken])
Creates a player for this stream
Parameters:
trackPath (String)
: the path of the track to be streamed e.g. /tracks/293secretToken (String, optional)
: a secret token for the track
Returns: A promise that will resolve with a player for the track
SC.Recorder(options)
The constructor function which returns an instance of the Web Audio Recorder (has to be called with new
)
Parameters:
-
options (Object, optional)
:context
: You can pass an AudioContext if you want to reuse itsource
: Pass a source if you want to record from an AudioNode
recorder.start()
Starts recording from the user's computer or the source
that was passed into the constructor
Requires the Web Audio API, Web Workers and getUserMedia to be available in the user's browser
recorder.stop()
Stops the current recording
recorder.play()
Plays back what was just recorded
Returns: The AudioNode that is used to play the sound
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 name of the file
recorder.delete()
Stops and deletes the recording
SC.Promise
The promise prototype that is used in the SDK internally (es6-promise). Use it to create your own promises or to use methods like Promise.all or Promise.race.
Player (methods & events)
Methods
You can use the methods below to control the player that is returned from SC.stream
play()
: Starts to play the sound. Returns a Promise that resolves when playback starts, and may reject if the browser refuses playback.pause()
: Pauses the playerseek(time)
: Seeks to the position in the song (in milliseconds). Returns a Promise that resolves when the seek completes, or may reject if the seek is not possible.currentTime()
: Returns the current position (in milliseconds)setVolume(volume)
: Sets the volume (from 0 to 1)getVolume()
: Returns the current volumegetDuration()
: Returns the duration (in milliseconds)isBuffering()
: Returns true whilst the player is bufferingisPlaying()
: Returns true whilst the intended state is to be playing. This flips withplay()
andpause()
calls.isActuallyPlaying()
: Returns true whilst the player is actually playinghasErrored()
: Returns true if the player is dead because of an errorisDead()
: Returns true if the player is deadgetState()
: Returns 'playing', 'paused', 'loading', 'ended', 'error' or 'dead'kill()
: Kill the player. Call this when you do not need it anymore.on(event, handler)
: Subscribes the handler to the given event
Events
You can subscribe to the events below by using the player's on(event, handler)
method.
state-change
: when audio controller changes state (e.g. from pause to play). Possible values: 'playing', 'paused', 'loading', 'ended', 'error' or 'dead'play
: whenplay
method is calledplay-start
: when playback actually starts, the first timeplay-resume
: when playback starts, the second time onwardsplay-rejection
: if a play request is rejected by the browserpause
: when playback is pausedfinish
: when sound is finishedseek
: whenseek
method is calledseeked
: when a seek completesseek-rejection
: when a seek is rejected for some reasongeo_blocked
: when there's no available streams for a sound, as it is not allowed to be played in the user's territory.buffering_start
: when buffering startsbuffering_end
: when buffering stopsaudio_error
: when an error occurstime
: when playback position is updatedno_streams
: when we failed fetching stream informationno_protocol
: when no supported protocol could be foundno_connection
: when we failed to connect to an endpoint due to missing transport or request timeout