RadioTime.js Documentation
Summary
TuneIn provides a thorough directory of audio stations and show schedules, logos and identifiers by supporting selection via location, search, and categorization.
RadioTime.js is a MIT-licensed JavaScript client to RadioTime‘s JSON/OPML API. Use of the RadioTime service is governed by our standard terms.
RadioTime.js is a new library and some interfaces are immature. If you have difficulty using it, we would love feedback on how to improve it. Patches happily accepted. No promise of API stability is yet appropriate.
Attributes and functions whose names begin with “_” should be considered private and not altered.
Requirements
RadioTime.js requires a browser host environment (i.e. access to the DOM) and should work in any A-Grade browser. It was originally designed to work with CE-HTML and should have a minimal resource footprint.
To use RadioTime.js, you will also need a TuneIn partner ID, which you can obtain from the developer’s page. Using a Partner ID provides the following benefits:
- Raises API limits placed on anonymous usage.
- Allows us to provide better support for your application.
- Allows application-specific server-side configuration and reserved features.
- Allows anonymous presets (based on your partner ID and a serial number) without account registration.
Due to current implementation limitations, you can only use one instance of RadioTime.js per page.
A persistent cookie named radiotime_serial is created to allow us to gather rough usage statistics and to provide persistent per-account presets (without explicit registration) via the API.
Additionally, if you would like to include audio playback, a media player is necessary. Several are provided, but you can supply your own as well.
Examples
See the examples directory for sample code using RadioTime.js.
Library Reference
RadioTime.$
An alias for document.getElementById.
RadioTime.debug
If opts.verbose is true, RadioTime.debug(…) issues library debugging information (via window.console or an element with ID “radiotime_log”.
Pass any number of arguments.
RadioTime.init
RadioTime.init initializes the library and as such must be called before any other functions in the API.
RadioTime.init(partnerId, containerId, path, opts)
| Parameter | Description | default |
|---|---|---|
| partnerId | your partner ID | required |
| containerId | A valid HTML ID | required |
| path | A full or relative URL from the host page to the path containing RadioTime.js itself. | required |
| opts.env | “beta” to use our Dev environment | “stable” |
| opts.formats | An array of formats to base responses on if no player is used. | RadioTime.player.formats |
| opts.useAMPM | Whether to display AM/PM or 24-hour times | true |
| opts.enableEvents | Whether to raise the events described below. | true |
| opts.history | See RadioTime.history | “internal” |
| opts.onHistoryChange | See RadioTime.history | undefined |
| opts.latlon | The user’s location, expressed as a string, e.g. “32.547,-97.383″ | location derived from IP address |
| opts.exactLocation | Strictly respect latlon, even if it falls in an area where IP address might give better results | false |
| opts.player | Your player implementation (see RadioTime.player below) | undefined |
| opts.noPlayer | Set to true if audio playback is not needed. The broadest stream selection can then be shown. | false |
| opts.verbose | Turns on debugging output via RadioTime.debug | false |
partnerId is a string that uniquely identifies your application.
containerId must identify an HTML element that RadioTime.js can use for internal operations (currently player embedding and script tags used for API transport).
path is used internally to create URLs from the host document to the URL for RadioTime.js. This is used to reference other files which RadioTime.js requires, such as the flash player. For example, if your host page was http://example.com and you placed the RadioTime.js source at http://example.com/rt-tools/RadioTime.js, then path should be either “http://example.com/rt-tools/” or “rt-tools/”.
opts.formats is only used if opts.noPlayer is true; otherwise, the selected player’s supported formats are used. If opts.noPlayer is true but opts.formats is not passed, wma and flash are used.
RadioTime.latlon
If set to a string with latitude and longitude in a string-delimited format, e.g. “32.547,-97.383″, this is passed as an explicit location for local API calls. If not set, the user’s IP is used for location.
RadioTime.loadJSON
RadioTime.loadJSON is a used by all the RadioTime.API functions to make requests to the RadioTime JSON API. If you need to use loadJSON directly, please consider filing a feature request for a more specific wrapper function.
RadioTime.loadJSON(url, success, failure)
| Name | Value |
|---|---|
| url | The API URL to request |
| success | See RadioTime.API |
| failure | See RadioTime.API |
RadioTime.API
RadioTime.API includes a collection of wrappers and convenience functions over the JSON API.
The API functions are asynchronous because they have to make network requests and would otherwise block the JavaScript UI thread. RadioTime.API methods always take success and failure functions, and may also take additional parameters specific to each call.
The success function receives two parameters – the body and the head of the JSON response, respectively. If a failure occurs due to server or network trouble, the failure receives no parameters; a failure due to a bad API call receives a head object.
Included parameters
RadioTime.js includes the following global parameters on each request:
| Name | Value |
|---|---|
| partnerId | init(partnerId) |
| serial | radiotime_serial cookie |
| formats | init(…,opts.formats) |
| locale | RadioTime.locale if defined |
| render | “json” |
| latlon | RadioTime.latlon if defined |
Other Global parameters
The username global parameter is currently unsupported by RadioTime.API. If you need to use it, please let us know. You can use RadioTime.loadJSON and RadioTime._formatReq for now.
RadioTime.API.getLocalStrings
Initializes string localizations from the RadioTime servers.
RadioTime.API.getLocalStrings(success, failure)
If you choose to localize your application, you can store your key-string mappings on the RadioTime servers. Calling this method will populate RadioTime.localStrings based on those keys and the requested locale.
Raises the loading with a parameter of “status_loading”.
Raises the custom localStrings event upon completion.
RadioTime.API.getRootMenu
Equivalent to Index Browse.
RadioTime.API.getRootMenu(success, failure)
Raises the loading with a parameter of “status_loading_menu”.
RadioTime.API.getCategory
Equivalent to Browse Category.
RadioTime.API.getCategory(success, failure, categoryId)
| Name | Value |
|---|---|
| categoryId | See below |
While there are many category IDs, most of these should be accessed through drill-down from the results of getRootMenu (whose results include URLs for category browse) because these IDs may not be stable over time.
However, this method may be useful for the following stable category names:
- lang
- local
- music
- podcast
- popular
- presets
- talk
- sports
- world
Raises the loading with a parameter of “status_loading”.
RadioTime.API.getStationSchedule
Equivalent to Browse Station Schedule.
RadioTime.API.getStationSchedule(success, failure, stationId)
| Name | Value |
|---|---|
| stationId | A station guide ID, e.g. s1000 |
You may prefer to use RadioTime.schedule which provides some convenience functions around schedule handling.
Raises the loading with a parameter of “status_loading_schedule”.
RadioTime.API.getProgramListeningOptions
Equivalent to Tune Show.
RadioTime.API.getProgramListeningOptions(success, failure, programId)
| Name | Value |
|---|---|
| showId | A show ID, e.g. p17 |
Raises the loading with a parameter of “status_loading”.
RadioTime.API.describe
Equivalent to Describe Station or Describe Show.
RadioTime.API.describe(success, failure, id)
| Name | Value |
|---|---|
| id | A show or station ID, e.g. p17 or s1000 |
Raises the loading with a parameter of “status_finding_stations”.
RadioTime.API.getOptions
Equivalent to Station or Show.
RadioTime.API.getOptions(success, failure, id)
| Name | Value |
|---|---|
| id | A show or station ID, e.g. p17 or s1000 |
Raises the loading with a parameter of “status_loading”.
RadioTime.API.getRelated
RadioTime.API.getRelated(success, failure, id)
Equivalent to Browse Station or show.
| Name | Value |
|---|---|
| id | A show or station ID, e.g. p17 or s1000 |
Raises the loading with a parameter of “status_loading”.
RadioTime.API.addPreset
Adds a station or show to presets.
RadioTime.API.addPreset(success, failure, id)
| Name | Value |
|---|---|
| id | A show or station ID, e.g. p17 or s1000 |
Equivalent to Preset with c=add.
Raises the loading with a parameter of “status_adding_preset”.
RadioTime.API.removePreset
Removes a station or show from presets. Equivalent to Preset with c=remove.
RadioTime.API.removePreset(success, failure, id)
| Name | Value |
|---|---|
| id | A show or station ID, e.g. p17 or s1000 |
Raises the loading with a parameter of “status_removing_preset”.
RadioTime.API.search
RadioTime.API.search(success, failure, query, filter)
Equivalent to Search.
| Name | Value | Default |
|---|---|---|
| query | String to query on | required |
| filter | “off” or “standard” | “standard” |
Raises the loading with a parameter of “status_searching”.
RadioTime.API.tune
Equivalent to Tune Station.
RadioTime.API.tune(success, failure, id)
| Name | Value |
|---|---|
| id | A show or station ID, e.g. p17 or s1000 |
Whether given a show or a station, the response is a list of candidate streams, restricted to the supported formats. If given a show, it must also be live.
RadioTime.API.getAccountStatus
Determine whether the application’s user has a RadioTime.com account.
RadioTime.API.getAccountStatus(success, failure)
Checks whether the client’s serial number is tied to a RadioTime.com account. Success receives an object {hasAccount: Boolean, text: String}.
If hasAccount, then text is the associated RadioTime.com account name. Otherwise, the text is a codeword.
The main benefit of joining an account is shared presets between multiple devices (even across partners). An application user with an existing account can add your device using the codeword at the device registration page.
Raises the loading with a parameter of “status_checking_account”.
RadioTime.API.getTime
Equivalent to Config Time.
RadioTime.API.getTime(success, failure)
Returns the current server-synchronized time, using your timezone offset.
Raises the loading with a parameter of “status_sync_time”.
RadioTime.player
Audio playback on the web is a little thorny, like video before YouTube. Since RadioTime does not control the format of the streams in its directory, the directory includes many kinds of playlists, container formats, and encodings. To learn more about these details, including recommendations of formats to prioritize, please see our Streaming Cookbook.
RadioTime.js includes player implementations for Flash, CE-HTML, and Songbird.
Player selection occurs when RadioTime.init is called and is dependent on the host browser environment. Once a player is selected, it implements the interface described below.
RadioTime.player.formats
A read-only array of formats supported by the player.
RadioTime.player.next
Advances the player to the next item in the playlist. If no next item is available, this is equivalent to calling stop.
RadioTime.player.next()
RadioTime.player.playerName
A short string identifying which player was selected. This is useful for debugging purposes. The default players are named “flash”, “ce”, and “songbird”. If you choose to supply your own player, please assign a playerName in its implementation.
RadioTime.player.startPlaylist
RadioTime.player.startPlaylist(playlistUrl)
Used to start playing a playlist, generally based on the URL of an outline[@type='audio'].
RadioTime.player.play
Plays or resumes playing a stream.
RadioTime.player.play(url)
| Name | Value | default |
|---|---|---|
| url | A stream URL to play | Resume playing a previously-paused stream |
If passed no parameters, resumes playing of a paused/stopped playlist. If passed a URL, plays that URL as a single-item playlist.
RadioTime.player.pause
Pauses playback.
RadioTime.player.pause()
RadioTime.player.stop
Stops playback.
RadioTime.player.stop()
Supplying your own player
If you would like to implement your own player, it is possible with the current implementation — just let us know and we’ll document this further.
RadioTime.schedule
RadioTime.js includes some convenience functions around time and station scheduling. Display of schedule information is, of course, time-sensitive, so internally, RadioTime.js synchronizes its time with the RadioTime service, respecting the host environment’s time zone, but correcting for any variation of the host clock with respect to the API.
RadioTime.schedule.init
Begin realtime schedule events.
RadioTime.schedule.init(stationId)
| Name | Value |
|---|---|
| stationId | A station ID, e.g. s1000 |
In order to begin receiving station scheduling information, subscribe to the “schedule” and/or “scheduleProgress” events (described below) and call RadioTime.schedule.init with a station guide_id (i.e. s1000).
The custom “schedule” event will be raised once immediately after the init call, and once per schedule change (i.e. when a new show begins). The custom “scheduleProgress” event is raised once per second, and is useful for timeline displays.
RadioTime.schedule.stopUpdates
Stop receiving the schedule events.
RadioTime.schedule.stopUpdates()
RadioTime.schedule can only be running for one station at a time, and calling RadioTime.schedule.init() implicitly stops updates on any prior station.
RadioTime.history
Typically in a web-based audio player, you don’t want to unload the web page upon user interaction, because doing so would also unload the audio player (interrupting playback) in the same page.
This can be addressed with popup windows or IFrames, but each have usability problems. Instead, RadioTime.history offers a couple choices for allowing navigation while remaining within a single DOM instance: “internal” or “hash”.
You must choose which form of history support you prefer when you call RadioTime.init. If you do use history support, you must also supply opts["onHistoryChange"] a function to be called on history transitions. Choose opts["history"] == “hash” if the user has access to browser chrome, specifically the back/forward/reload buttons. Choose “internal” if not. If you prefer to provide your own player continuity, or you don’t plan on playing audio, you should choose “internal”.
Normal user interaction should result in a call to RadioTime.history.add. A history transition occurs when the back or forward button of the browser is clicked, or when RadioTime.history.back() is called.
Finally, when using opts["history"] == “hash”, you must also include a reference to the rsh.js included in this library, e.g.
<script src="rt-tools/js/rsh.js"></script>
<script src="rt-tools/js/radiotime.js"></script>
This rsh.js is a minified and slightly modified version of Really Simple History.
RadioTime.history.add
Add some state to the history.
RadioTime.history.add(state)
| Name | Value |
|---|---|
| state | An object containing your application’s state |
History entries in normal browser usage are created by user navigation, and form a basis for the user to undo or go back. In your application, when such an interaction occurs, you should store information relevant to that transition.
For example, you may wish to store the category ID that a user was browsing prior to choosing a specific station, or the search term before a specific search result.
Whatever information you choose to store can be placed into history by passing that object to RadioTime.history.add.
onHistoryChange
A function you supply (as RadioTime.init opts.onHistoryChange) which restores the application to a previous state.
onHistoryChange(state)
When history is manipulated (such as when the user clicks the back button, or you call RadioTime.history.back(), this function is called with state previously stored via RadioTime.history.add(state).
RadioTime.history.back
Navigates back in history.
RadioTime.history.back()
RadioTime.history.last
Return the most recently stored object from history.
RadioTime.history.last()
This does not alter history — it only returns the most recent state.
RadioTime.history.reset
Reset history (if using “internal” history).
RadioTime.history.reset()
This does not call onHistoryChange.
RadioTime.event
RadioTime.event implements a lightweight cross-browser eventing system similar to DOM events, but supporting events related to playback and API response loading. It does not support bubbling but does support object-specific dispatch. For example, an event might be fired many times, but only a few times in relation to a specific object.
Passing a opts.enableEvents value of false to RadioTime.init disables events. You may wish to do this for performance reasons.
See Custom Events for details on the events RadioTime.js supplies.
RadioTime.event.subscribe
Subscribe to a custom event.
RadioTime.event.subscribe(eventName, handler, forObj)
| Parameter | Description | default |
|---|---|---|
| eventName | string | required |
| handler | function(params) | required |
| forObj | limit raises to the specific object | undefined |
Subscribe to all eventName events, to be handled by handler, but only for the object forObj (if given). Returns a handler ID, which should be retained if you later wish to unsubscribe.
RadioTime.event.raise
Raise a custom event.
RadioTime.event.raise(eventName, params, toObj)
| Parameter | Description | default |
|---|---|---|
| eventName | string | required |
| params | An event-specific parameter object | required |
| toObj | Narrows the scope of the event to a specific object | undefined |
Raise an event, perhaps to only one object out of many possible recipients. If toObj is given, the handlers will be called with toObj as “this”.
RadioTime.event.unsubscribe
Unsubscribe from an event.
RadioTime.event.unsubscribe(handlerId)
| Name | Value |
|---|---|
| handlerId | An ID previously returned from RadioTime.event.subscribe |
RadioTime.locale
Specify a locale other than the browser’s default.
By default, the API respects the HTTP Accept-Language header, but RadioTime.locale can be set to an ISO 639 code (such as en-US), which is then passed as the locale global parameter in API requests. See the API locales documentation for more information.
RadioTime.L
Get a localized string.
RadioTime.L(string)
| Name | Value |
|---|---|
| string | A native token to localize |
After calling RadioTime.API.getLocalStrings, you can use RadioTime.L to return a localized string or the given string itself.
For example, if RadioTime.localStrings includes {‘hello’:'hola’}, RadioTime.L(‘hello’) would return ‘hola’, but RadioTime.L(‘what’) would return ‘what’.
RadioTime.response
RadioTime.response includes a family of functions to help in interpreting and reacting to API responses.
RadioTime.response.audio
Get only audio elements.
RadioTime.response.audio(body)
Given an API response, returns a flattened list of objects which represent audio streams.
RadioTime.response.flatten
Flatten the tree of objects into a simple array.
RadioTime.response.flatten(body, copyKey)
| Name | Value | default |
|---|---|---|
| body | An outline element | required |
| copyKey | Whether to copy parent’s key attribute to children | false |
Sometimes, you’ll want to flatten the nesting that’s included in the API responses. RadioTime.resonse.flatten() returns a flat Array containing the original outline and all children.
Some outline elements (with type of “text” or “link”) have key attributes which are useful for programmatic processing, and flattening loses the parent/child context necessary for correct processing. If you’d prefer to preserve the parent’s key on child elements, you can pass copyKey = true.
RadioTime.response.station
Get only station elements.
RadioTime.response.station(body)
Given an API response, returns a flattened list of objects which represent stations.
Ancillary
Time
As part of initialization, the offset of the client’s time with respect to the server’s time is determined.
- RadioTime.gmtOffset is the number of minutes from GMT the client’s timezone is in.
- RadioTime.tzName is a string name for the detected time zone.
- RadioTime.timeCorrection is the number of milliseconds from the client’s time to the server’s time (within the detected time zone).
- RadioTime.now() returns a Date object synchronized with the server’s time.
- RadioTime.formatTime(time) returns a string version of the given or current time, based on RadioTime.useAMPM.
RadioTime.getLogoUrl
Get a related logo.
RadioTime.getLogoUrl(guideId, logoSize, logoFormat)
| Name | Value | default |
|---|---|---|
| guideId | Station or Guide ID | required |
| logoSize | “square”, “small”, “normal” | “normal” |
| logoFormat | “png”, “gif” | “png” |
Given a station or show ID, this returns the URL for a logo.
RadioTime.getTuneUrl(id)
Get the URL for a Tune call.
RadioTime.getTuneUrl(id)
Given a ID, returns a URL string equivalent to a Station Tune.
RadioTime.makeId
Get a unique number for use in IDs.
RadioTime.makeId()
RadioTime.merge
Merge one object’s properties into another’s.
RadioTime.merge(target, source, useSuper)
| Name | Value |
|---|---|
| target | The object to merge to |
| source | The attributes to merge from |
| useSuper | Whether to support superclass methods |
RadioTime.merge implements a sort of class-based inheritance. For each attribute on source, it is copied to target if target does not already have an attribute of that name. if useSuper is true, then the overridden attribute on source is made available via target.callSuper(attributeName).
Since this function operates on objects, it can also be used to merge dictionaries, e.g.
- x = {‘a’:'subclass a’, ‘b’:'subclass b’}
- y = {‘a’:'superclass a’, ‘c’:'superclass c’}
- RadioTime.merge(x, y)
- x.a === ‘subclass a’
- x.b === ‘subclass b’
- x.c === ‘superclass c’
RadioTime.cookie
Implements some convenience functions over cookies.
RadioTime.cookie.save
Save a value to a cookie.
RadioTime.cookie.save(name, value, days)
| Name | Value |
|---|---|
| name | The name of the cookie |
| value | The value to store |
| days | How many days to store it |
RadioTime.cookie.read
Read a value from a cookie.
RadioTime.cookie.read(name)
| Name | Value |
|---|---|
| name | The name of the cookie to read |
Reads the value of a cookie.
RadioTime.cookie.clear
Remove a specific cookie.
RadioTime.cookie.clear(name)
| Name | Value |
|---|---|
| name | The name of the cookie to remove |
getUpdate
This is an adapter shim for the supplied flash player. For internal use only.
Custom Events
schedule
Fired when a new schedule is available, and each time the current show changes.
The parameter for this event is the result of the API getSchedules call.
scheduleProgress
Fired once per second while RadioTime.schedule is in use.
The parameter for this event is the current show’s { guide_id: String, item: {text: String, start: Date, end: Date} }
playlistEnded
Fired when a player reaches the end of its playlist. For streams, this should not occur unless there is a stream failure, but it may occur when the end of an on-demand topic is reached.
This event receives no parameter.
playstateChanged
Fired by the player implementation upon playback transitions.
The parameter is the state the player is entering and is player dependent, but at a minimum, the following states must be raised: “stopped”, “playing”, “paused”.
loading
Fired by the API before each asynchronous call.
The parameter to this event is a string whose value depends on the type of load. See the RadioTime.API documentation for specific values.
loaded
Fired after a successful API network call, regardless of whether the API status was successful.
This event receives no parameter.
failed
Fired after a failed API network call.
This event receives no parameter.
localStrings
Fired after getLocalStrings and should be used to notify the library if RadioTime.localStrings is manually updated.
This event receives no parameter.
flashEvent
Fired by the Flash player implementation, and consumed by the RadioTime.player Flash support.
Debugging
If you need to debug your RadioTime.js application, here are some helpful tips:
- Pass opts.verbose = true to RadioTime.init so that the library itself writes debug information.
- Make sure window.console (or an element with ID radiotime_log is available for RadioTime.debug to write to.
- Use browser developer tools where available.
- Liberally use RadioTime.debug in your application.
- Make sure to supply failure callbacks in your API calls.
