Home
Table of contents
- Introduction
- Quick start
- Embed code
- Properties
- Methods
- Widget events
- JavaScript Frameworks
- Appendix
- Licensing
Introduction
A JavaScript based API for the SoundCloud player Widget.
Quick start
To try out the SoundCloud Widget API, please download or check out the soundcloud.player.api.js file and put it into your scripts folder.
Put the following code into your HTML head:
<script type="text/javascript" src="scripts/soundcloud.player.api.js"></script>
<script type="text/javascript">
soundcloud.addEventListener('onPlayerReady', function(player, data) {
player.api_play();
});
</script>Put the following code into your HTML
body:<object height="81" width="100%" id="yourPlayerId" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000">
<param name="movie" value="http://player.soundcloud.com/player.swf?url=http%3A%2F%2Fsoundcloud.com%2Fmatas%2Fhobnotropic&enable_api=true&object_id=yourPlayerId"></param>
<param name="allowscriptaccess" value="always"></param>
<embed allowscriptaccess="always" height="81" src="http://player.soundcloud.com/player.swf?url=http%3A%2F%2Fsoundcloud.com%2Fmatas%2Fhobnotropic&enable_api=true&object_id=yourPlayerId" type="application/x-shockwave-flash" width="100%" name="yourPlayerId"></embed>
</object>
When you’ll open this page, the SoundCloud widget will load and start playing immediately.
Also, while you at your test drive, it’s highly recommended to temporarily enable debugging by prepending the script with soundcloud.debug = true; and opening that page in Firefox with Firebug extension enabled. This way you’d get a better idea how and when the events get fired, if the embed code is correct etc.
Important: Because of the Flash local sandbox restrictions, the API will work only on a web server. This means, you’ll either need to put the following example in the folder that’s accessible through a local web server (e.g. http://127.0.0.1/, http://localhost/ etc.) or upload it to a remote server.
Embed code
To be able to use the Widget API, you’ll have to modify the standard embed code accordingly. First, choose a name you’ll refer to the player, for example myPlayer.
- set the
objecttagidattribute tomyPlayer - set the
embedtagnameattribute tomyPlayer - add a query parameter
object_id=myPlayerto a widget url - activate widget event callbacks by adding a query parameter
enable_api=true - add a
classidparameter to theobjecttag for the Internet Explorerclassid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
<object height="81" width="100%" id="myPlayer" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"> <param name="movie" value="http://player.soundcloud.com/player.swf?url=http%3A%2F%2Fsoundcloud.com%2Fmatas%2Fhobnotropic&enable_api=true&object_id=myPlayer"></param> <param name="allowscriptaccess" value="always"></param> <embed allowscriptaccess="always" height="81" src="http://player.soundcloud.com/player.swf?url=http%3A%2F%2Fsoundcloud.com%2Fmatas%2Fhobnotropic&enable_api=true&object_id=myPlayer" type="application/x-shockwave-flash" width="100%" name="myPlayer"></embed> </object>
Please make sure that the id and name attributes of the object and embed tags do not include the following characters: . - + * / \. read the ExternalInterface documentation
These settings are mandatory. If you’re using SWFObject or similar Flash HTML generators, set id to the widget identifier, and also add enable_api:true, object_id:"yourPlayerId" to the flashvars object. You shouldn’t need to add a classid parameter, the generator will create it by itself in Internet Explorer.
var flashvars = {
enable_api: true,
object_id: "myPlayer",
url: "http://soundcloud.com/forss/flickermood"
};
var params = {
allowscriptaccess: "always"
};
var attributes = {
id: "myPlayer",
name: "myPlayer"
};
swfobject.embedSWF("http://player.soundcloud.com/player.swf", "myContent", "81", "100%", "9.0.0","expressInstall.swf", flashvars, params, attributes);
Also note, that
allowscriptaccess attribute is set to always.
Properties
soundcloud.version
returns a current wrapper version as a string in format major.minor, e.g. '0.1'. Minor version will keep the same API, major version changes may change the API.
soundcloud.debug
Enable event tracing to window.console by setting this property to true. The default setting is false.
Methods
The Widget API wrapper will create a global variable soundcloud.
Wrapper methods
soundcloud.addEventListener(eventName, function)
Requires 2 arguments – event type and listener function.
Add an event listener to a player, gets notified about the changes. The listener function will receive 2 arguments – widget DOM node and the data object. Please refer to the Events documentation to find out more about the data sent with particular events.
soundcloud.addEventListener('onPlayerReady', myEventHandlerFunction);
soundcloud.removeEventListener(eventName, function)
Requires 2 arguments – event type and listener function.
soundcloud.removeEventListener('onPlayerReady', myEventHandlerFunction);
soundcloud.getPlayer(playerID)
Requires 1 argument – flash element ID. Normally it’s the
id attribute of the object tag and name attribute of the embed tag in HTML.Returns a DOM object of the player, the widget methods are available. In case the embed code wasn’t set up correctly, this method will throw an error indicating the reason.
var player = soundcloud.getPlayer('myPlayerId');
Widget methods
When you’ll get the widget DOM object with the help of the soundcloud.getPlayer method, you’ll have access to the following public methods:
api_play()
Player starts playing either from 0 or from the last paused track position. In the case the widget contains multiple tracks it will start playing the first track.
api_pause()
Player stops playing, current track position is saved.
api_stop()
Player stops playing, current track position is reset to 0.
api_toggle()
Player starts or stops playing, depending on it’s current state. The current track position is saved.
api_prev()
In the case the widget contains multiple tracks it will skip to the previous track.
api_next()
In the case the widget contains multiple tracks it will skip to the next track.
api_skip(trackIndex)
In the case the widget contains multiple tracks it will jump to the trackIndex, where the track list goes 0,1,2. e.g. myPlayer.api_skip(2) will load the third track in a playlist. You can check the current trackIndex by calling myPlayer.api_getCurrentTrackIndex().
api_load(url)
Player stops playing, resets and loads a new resource from the given url. This way one widget could be used as an audio engine for the multiple SoundCloud resources. Note: after calling this method, please wait again for the onPlayerReady event! Only after it’s been triggered the player is operational again.
api_seekTo(seconds)
Jump to a certain position in a track. Before seeking into track, please make sure that the track is fully buffered. The widget will trigger a onMediaDoneBuffering event when it’s fully available.
api_setVolume(0..100)
Set the widget volume to a certain value.
api_getVolume()
Returns current volume, as a number between 0 and 100.
api_getTrackDuration()
Returns current track duration in seconds.
api_getTrackPosition()
Returns current track position in seconds.
api_getTracks()
Returns the list of the track objects in the player
api_getCurrentTrack()
Returns the current track object
api_getCurrentTrackIndex()
Returns the index of the current track in the playlist (0 based). If the first track is playing it’ll return 0, the second 1, and so on.
api_getFlashId()
Returns the id/name of the widget node in the DOM.
Did you know, that you can’t useplayorstopwhen registering callbacks throughExternalInterface.addCallback()in Flash? The Internet Explorer would throw an error on line 48 “object does not support this property”. Read about it here or here
Widget events
If the player’s enable_api parameter is set to true (see Embed code) the widget will trigger certain events. You can listen to these events using the soundcloud.addEventListener method. If you have access to JavaScript frameworks jQuery or Prototype in your web application, you can use the respective listener methods.
Listener arguments
The registered listener functions should expect 2 arguments:
player DOM node
the widget DOM node that triggered this event, should be used to reference the widget especially when you have a few of them on the page.
data Object
this object will always contain the following properties:
- mediaUri String: the uri of media in Widget API that triggered the event, like ‘http://api.soundcloud.com/tracks/49931’
- mediaId String: the id of the media item, e.g. ‘49931’ etc.
The load events onMediaBuffering and onMediaDoneBuffering have an additional property in data: - percent Number: a percent of the current track audio stream in local buffer, from 0 to 100
These properties should help you reference the items in SoundCloud API. Let’s say on onPlayerReady you get a data.mediaUri http://api.soundcloud.com/tracks/49931, then you could call it for more info etc. Check out the jQuery example in examples folder for working example code.
Event types:
onPlayerReady
Fired when the widget has loaded its data and is ready to accept external calls. Triggered only once per widget instance.
soundcloud.addEventListener('onPlayerReady', function(player, data) {
console.log('player ready');
});
onMediaStart
Fired when the widget starts playing current track (fired only once per track).
soundcloud.addEventListener('onMediaStart', function(player, data) {
console.log('track started id:' + data.mediaId);
});
onMediaPlay
Fired when the widget plays current track.
soundcloud.addEventListener('onMediaPlay', function(player, data) {
console.log('track is playing id:' + data.mediaId);
});
onMediaPause
Fired when the widget stops playing current track (fired on every play, seek, toggle from pause)
soundcloud.addEventListener('onMediaPause', function(player, data) {
console.log('track stopped at:' + player.api_getTrackPosition());
});
onMediaBuffering
Fired when the widget is still buffering. data (second argument) contains property percent. It also means you can’t seek in the track fully yet
soundcloud.addEventListener('onMediaBuffering', function(player, data) {
console.log('track loading:' + data.percent + '%');
});
onMediaDoneBuffering
Fired when the widget is done buffering. data (second argument) contains property percent. It also means now you can seek in the track.
soundcloud.addEventListener('onMediaDoneBuffering', function(player, data) {
console.log('track loaded!');
player.api_seekTo(35);
});
onPlayerError
Fired when the widget can’t get the requested data from the server (the resource is removed, hidden, etc.). The widget initialization failed.
soundcloud.addEventListener('onPlayerError', function(player, data) {
console.error('track couldn't be loaded!');
});
JavaScript Frameworks
The widget wrapper will automatically re-trigger every widget event into the DOM as a jQuery or Prototype event. The events are name spaced in the format ‘soundcloud:eventName’, e.g. ‘soundcloud:onPlayerReady’.
jQuery integration
$(document).bind('soundcloud:onPlayerReady', function(event, data) {
var mediaUri = data.mediaUri,
mediaId = data.mediaId,
flashNode = event.target;
});
Prototype integration
$(document).observe('soundcloud:onMediaPlay', function(event) {
var mediaUri = event.memo.mediaUri,
mediaId = event.memo.mediaId,
flashNode = event.target;
});
Please note the difference in the listener parameters. The event is triggered off the widget DOM node so the flash object can be accessed as event.target in listener function.
Appendix
Track Object
The widget methods api_getTracks and api_getCurrentTrack return custom track objects that contain certain properties:
artwork: "http://i1.soundcloud.com/artworks-000000103093-941e7e-large.jpg?4ef4a5"
bpm: "84"
commentCount: 7
commentable: true
comments: Array
createdAt: "2008/10/27 09:56:47 +0000"
description: "Kinda of an experiment in search for my own sound. I've produced this track from 2 loops I've made u…"
downloadCount: 280
downloadUrl: null
downloadable: false
duration: 489138
id: "49931"
label: null
labelUrl: null
license: "by-nc"
loaded: false
permalink: "hobnotropic"
permalinkUrl: "http://soundcloud.com/matas/hobnotropic"
playbackCount: 605
purchaseUrl: null
releaseDate: null
streamUrl: "http://media.soundcloud.com/stream/IqSLUxN7arjs"
streamable: true
timedComments: Array
title: "Hobnotropic"
type: "track"
uri: "http://api.soundcloud.com/tracks/49931"
user: Object
videoURL: null
waveform: "http://waveforms.soundcloud.com/IqSLUxN7arjs_m.png"
It could be used as a short-hand access to the track data. Please keep in mind, that we strongly recommend fetching the track info from the SoundCloud API instead. The track object structure here can change, whereas main API structure is better documented and more stable.
Licensing
The project is published under an MIT license:
Copyright © 2009 SoundCloud Ltd.
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the “Software”), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
