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 Usage
- Authentication
- API
- Streaming
- Recording
- Uploading
- Embedding
- Examples
- Promises
- API Documentation
- Player (methods & events)
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 idredirect_uri(optional): Required only for user authenticationoauth_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 idredirect_uri: The redirect URI defined in your app settingsscope: 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/183params (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/followingsparams (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./meparams (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 recordingprogress (Function): Progress callback- Accepts all other upload request params such as
artwork_dataorsharing(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 SoundCloudparams (Object, optional): Additional oEmbed parameters (see oEmbed docs). Accepts anelementproperty 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/293secretToken (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 reusesource: 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 playerseek(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 millisecondssetVolume(volume): Sets volume (0 to 1)getVolume(): Returns the current volumegetDuration(): Returns the duration in millisecondsisBuffering(): Returns true while bufferingisPlaying(): Returns true while the intended state is playing (flips withplay()andpause())isActuallyPlaying(): Returns true while actually playinghasErrored(): Returns true if the player has encountered a fatal errorisDead(): Returns true if the player is deadgetState(): 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:playmethod calledplay-start: Playback starts for the first timeplay-resume: Playback starts on subsequent playsplay-rejection: Browser rejects a play requestpause: Playback pausedfinish: Sound finishedseek:seekmethod calledseeked: Seek completesseek-rejection: Seek rejectedgeo_blocked: No streams available for the user's territorybuffering_start: Buffering startsbuffering_end: Buffering stopsaudio_error: An error occurstime: Playback position updatedno_streams: Failed to fetch stream informationno_protocol: No supported protocol foundno_connection: Failed to connect due to missing transport or request timeout