Adaptr SDK

Adaptr Music Player SDK for Javascript

Introduction

The Adaptr SDK for Javascript allows you to play commercial music published via the adaptr.com website.

This javascript library makes use of the Audio element and works with all browsers that support it: Edge 17+, Firefox 61+, Chrome 51+, and Safari 11.1+.

NOTE - we do NOT support mobile web browsers using our Javascript SDK. While the Javascript SDK may have some success on mobile web browsers, we do not officially support these mobile web integrations due to frequent platform bugs and limitations. To create the best user experience, we recommend understanding these limitations prior to developing on mobile web. In general, Adaptr best practices discourage the use of our Javascript SDK on mobile web to ensure the applications you develop are optimized for the best possible user experience. We recommend building native mobile applications which can utilize our iOS SDK and Android SDK.

Installation

Via npm

Install via npm:

npm install @adaptr/web-sdk

Use <script> tag

The dist/adaptr-script.js file in this package is suitable for including directly in an HTML page. This is a self-executing function that exposes a global Adaptr variable to your javascript. The file has no external dependencies.

CJS or ES Modules

Alternatively, if you're using a bundler, add the following to your code:

var Adaptr = require("@adaptr/web-sdk");

or

import Adaptr from "@adaptr/web-sdk";

Usage

Full documentation on all classes and interfaces is available here.

Concepts and Operation

All interaction is done through a Adaptr.Player instance. A player instance must be initialized with a token/secret pair, which it presents to the adaptr servers to retrieve a list of available music stations. Those stations map directly to playlists that were created and published using the adaptr dashboard.

The player can be instructed to stream music from a given station or the player can be used to list and search for individual song tracks (referred to as audio files in the SDK) in those stations. Lists of tracks can be handed to the player for queued playback.

During playback, the player emits numerous events to enable monitoring and rendering UI elements.

Initialization

The Adaptr.Player class retrieves music from the Adaptr servers and sends them to the browser for playback. Adaptr.Player exposes simple play(), pause(), and skip() methods to start, stop, and advance music playback. The player plays songs in sequence from either a station (which is what playlists published via the Adaptr dashboard are represented as), or from a local play queue containing individual songs selected from those stations.

The SDK is initialized like so:

let player = new Adaptr.Player("adaptr", "adaptr");
player
.initialize()
.then(({ stations }) => {
// player successfully initialized.
})
.catch(() => {
// player unsuccessfully initialized, likely due to licensing
// restrictions. No music is available for playback.
});

The player is initialized by passing it your token and secret credential values provided in the Adaptr dashboard. For test purposes, you can use adaptr as your token and secret.

The call to initialize() causes the player to contact the Adaptr servers, validate credentials, and retrieve the list of stations that is has access to.

The player may not successfully initialize if the end user isn't in a location licensed to play the music for the given credentials, so it is important to handle this exception.

If you'd rather not use promises, the player emits events that can be listened to via the on() method.

let player = new Adaptr.Player("adaptr", "adaptr");

player.on("stations", (stations) => {
// music is available for playback!
});

player.on("music-unavailable", () => {
// music is not available for playback
});

player.initialize();

For a very simple example of the player in action, check out this jsbin.

Station playback

A call to playStation(stationName) will begin immediate playback of music from the station with name stationName. An exception will be thrown if no station with the given name exists. The available station names can be found in the stations array returned from the initialize() promise, the getStations() method, or the stations event.

The following code renders an HTML list, where each item represents one of the available stations. When an item is clicked on, playback of the station begins.

<ul id="station-list"></ul>

<script>
let stationList = document.getElementById("station-list");

let player = new Adaptr.Player("adaptr", "adaptr");

player
.initialize()
.then(({ stations }) => {
let items = stations.map((station) => {
return '<li data-name="' + station.name + '">' + station.name + "</li>";
});

stationList.innerHTML = items.join("");

document.getElementById("station-list").addEventListener(
"click",
(event) => {
if (event.target.dataset.name) {
player.playStation(event.target.dataset.name);
}
},
true
);
})
.catch(() => {
stationlist.innerHTML = "<li>Sorry - no music for you!</li>";
});
</script>

You can run the above code in this jsbin.

We can add some more interactivity with play/pause and skip buttons that are implemented with the play(), pause(), skip(), and stop() methods, and by watching the playback events triggered by the player:

<button id="play-pause-button" disabled>play</button>
<button id="skip-button" disabled>skip</button>
<button id="stop-button" disabled>stop</button>

<script>
//
// ... initialization code from previous example
//

let playPauseButton = document.getElementById("play-pause-button");
let skipButton = document.getElementById("skip-button");
let stopButton = document.getElementById("stop-button");

playPauseButton.addEventListener("click", () => {
if (player.getCurrentState() === "playing") {
player.pause();
} else {
player.play();
}
});

skipButton.addEventListener("click", () => {
player.skip();
});

stopButton.addEventListener("click", () => {
player.stop();
});

player.on("playing", () => {
playPauseButton.innerHTML = "pause";
playPauseButton.disabled = false;
skipButton.disabled = false;
stopButton.disabled = false;
});

player.on("paused", () => {
playPauseButton.innerHTML = "play";
});

player.on("idle paused", () => {
skipButton.disabled = true;
});

player.on("idle", () => {
stopButton.disabled = true;
});
</script>

The code above starts playback of a station when you click on it, and you can pause, resume, and skip songs via the buttons. You can also stop playback of the current station with the stop button.

Check out this jsbin to see that code in action.

Discovering Individual Songs

The player can be used to discover individual tracks that can be added to a play queue and handed to the player for playback.

Tracks can be discovered by paginating through the available stations:

let station = player.getStations()[0];
// search for the first 10 tracks in this station:
player.fetchAudioFilesInStation(station.name, 0, 10).then((results) => {
console.log(
`This station has a total of ${results.total} tracks. The first 10 are:`,
results.audioFiles
);
});

Note that page indices begin at '0'. See this jsbin for example code that retrieves the contents of the demo music stations.

Tracks can also be discovered through search:

  player.searchAudioFiles('time', { perPage: 10 });
.then((search) => {
console.log(`We found ${search.total} matching tracks. The first 10 are:`, search.results);
});

See this jsbin for an example search script.

On-Demand Queued Playback

The audioFile entries returned through search and station fetching can be queued in the player, so that they play as if they were a station:

let station = player.getStations()[0];

player.fetchAudioFilesInStation(station.name, 0, 10).then((results) => {
// play the 2nd and 5th song
player.playAudioFiles([results.audioFiles[1], results.audioFiles[4]]);
});

This jsbin queues up all the songs from the result of a search for playback.

When all the songs in the queue have been played, the player will transition to the 'idle' state and emit a 'music-exhausted' event.

Initializing Audio on User Event

Modern web browsers require that audio playback be initialized in a user event handler. This means that auto-play of music on page load isn't possible. This also means, for the Adaptr player to work, you must call an Adaptr method from within a user-triggered event handler. Specifically, you must call playStation(), playAudioFiles() or initializeAudio() from that event handler. The initializeAudio() method doesn't start any music and it is safe to call multiple times without affecting playback, so we recommend calling initializeAudio() from any available user-triggered event handler on a page.

SDK Docs!

The full docs for the SDK are located here.

Generated using TypeDoc