# arozcast.js — SDK Reference
`arozcast.js` is a ready-made JavaScript client for ArozOS webapps that want to send media to an Arozcast receiver screen. It wraps the raw WebSocket API (documented in `README.md`) and handles connection management, heartbeating, exponential-backoff reconnection, and cross-tab coordination so you don't have to.
---
## Table of Contents
1. [Setup](#setup)
2. [Quick Start](#quick-start)
3. [Constructor](#constructor)
4. [Lifecycle Methods](#lifecycle-methods)
- [connect()](#connectcode)
- [disconnect()](#disconnect)
- [destroy()](#destroy)
- [ping()](#pingcode)
- [notifyTakeover()](#notifytakeover)
- [isConnected()](#isconnected)
5. [Playback Commands](#playback-commands)
- [load()](#loadtrack)
- [play()](#play)
- [pause()](#pause)
- [seek()](#seektime)
- [seekRel()](#seekreldelta)
- [setVolume()](#setvolumelevel-muted)
- [setRepeat()](#setrepeatmode)
- [stop()](#stop)
- [send()](#sendtopic-payload)
6. [Events](#events)
7. [Properties](#properties)
8. [Integration Patterns](#integration-patterns)
- [Basic audio player](#basic-audio-player)
- [Video player with seek bar](#video-player-with-seek-bar)
- [Playlist with repeat modes](#playlist-with-repeat-modes)
- [Reconnect UI feedback](#reconnect-ui-feedback)
- [Handing off to another app](#handing-off-to-another-app)
9. [Lifecycle Diagram](#lifecycle-diagram)
10. [Comparison: SDK vs Raw API](#comparison-sdk-vs-raw-api)
---
## Setup
Copy `arozcast.js` from `src/web/Arozcast/` into your webapp, or reference it with a relative path:
```html
```
No bundler or npm install required. The class is attached to `window.ArozCast` after the script loads.
---
## Quick Start
```javascript
// 1. Create one instance for your app's cast session
const cast = new ArozCast({ aoRoot: ao_root });
// 2. Listen for events
cast
.on('connect', ({ code }) => updateUI('Connected to room ' + code))
.on('disconnect', ({ code }) => updateUI('Lost connection — retrying…'))
.on('giveup', ({ code }) => resumeLocally())
.on('status', (s) => updateProgress(s.currentTime, s.duration))
.on('ended', () => playNextTrack());
// 3. Check the room is alive, then connect
const code = prompt('Enter Arozcast room code:');
cast.ping(code).then(exists => {
if (!exists) { alert('Room not found'); return; }
cast.connect(code).then(() => {
// 4. Send the current media item
const vid = document.getElementById('my-video');
cast.load({
name: currentEpisode.name,
type: 'video',
src: currentEpisode.streamUrl, // full playback URL
filepath: currentEpisode.filepath, // ArozOS virtual path
startTime: vid.currentTime // sync mid-playback
});
cast.setVolume(vid.volume * 100, vid.muted);
cast.play();
vid.pause(); // local video hands off to receiver
});
});
// 5. Explicit user disconnect
document.getElementById('disconnect-btn').addEventListener('click', () => {
const pos = /* save current position from status event */;
cast.disconnect();
resumeLocallyAt(pos);
});
```
---
## Constructor
```javascript
const cast = new ArozCast(options);
```
| Option | Type | Default | Description |
|--------------------|------------|------------------------|-------------|
| `aoRoot` | `string` | global `ao_root` or `/` | ArozOS root URL. Pass `ao_root` (set by `ao_module.js`) when available. |
| `reconnectDelays` | `number[]` | `[2000, 5000, 12000]` | Millisecond delays before each reconnection attempt. Three entries = three attempts. Pass `[]` to disable auto-reconnect entirely. |
```javascript
// Custom backoff (5 attempts)
const cast = new ArozCast({
aoRoot: ao_root,
reconnectDelays: [1000, 3000, 8000, 15000, 30000],
});
// Auto-reconnect disabled
const cast = new ArozCast({ aoRoot: ao_root, reconnectDelays: [] });
```
---
## Lifecycle Methods
### `connect(code)`
Connects to an existing Arozcast room and announces the sender.
- Cancels any pending auto-reconnect to the previous room.
- Broadcasts `arozcast.takeover` so other open sender apps (Musicify, Movie, Photo) release their sessions.
- Sends `peer.hello` and starts the heartbeat on success.
```javascript
cast.connect('1234')
.then(() => { /* socket open, peer.hello sent */ })
.catch(err => console.error('Failed to connect:', err.message));
```
**Returns:** `Promise` — resolves when the WebSocket is open, rejects if the server refuses the connection or the 8-second handshake times out.
> After `connect()` resolves, always send `load()`, `setVolume()`, then `play()` in that order.
---
### `disconnect()`
Explicitly disconnects from the current room.
- Sends `media.stop` to clear the receiver's screen.
- Cancels any pending auto-reconnect.
- Sets `cast.connected = false` and `cast.code = null`.
Use this when the **user** actively chooses to stop casting (e.g. clicks "Stop Cast"). Do **not** call this on page unload — use `destroy()` or let `beforeunload` handle it automatically.
```javascript
function stopCasting() {
const resumeAt = lastStatusTime; // saved from 'status' event
cast.disconnect();
resumeLocalVideoAt(resumeAt);
}
```
---
### `destroy()`
Releases all resources held by this instance without notifying the receiver.
- Removes `visibilitychange` and `beforeunload` listeners added in the constructor.
- Closes the BroadcastChannel.
- Closes the WebSocket silently — **does not** send `media.stop`, so the receiver keeps playing.
Called automatically on `beforeunload`. Call it manually only if you need to tear down the instance while the page is still open (e.g. unmounting a component).
```javascript
// Clean up when navigating away within a SPA
onRouteChange(() => cast.destroy());
```
---
### `ping(code)`
Checks whether a room with the given code is currently active.
```javascript
const exists = await cast.ping('1234');
if (exists) { /* safe to connect */ }
```
**Returns:** `Promise`
Call this before `connect()` to give the user a clear error message instead of a silent timeout.
---
### `notifyTakeover()`
Broadcasts `arozcast.takeover` on the `BroadcastChannel('arozcast')` channel, signalling all other open sender tabs to release their sessions.
Called automatically by `connect()`. Call it manually if your app starts a new session through a path that bypasses `connect()` (e.g. a deep-link handler).
```javascript
// Taking over from a non-SDK code path
myLegacyCastWs = new WebSocket(url);
cast.notifyTakeover(); // silence other senders
```
---
### `isConnected()`
Returns `true` when the WebSocket is open and ready to accept messages.
```javascript
if (cast.isConnected()) {
cast.seek(42);
} else {
myVideo.currentTime = 42;
}
```
Equivalent to checking `cast.connected`, but safe to call at any time.
---
## Playback Commands
All commands are silently dropped if the socket is not open. There is no queue — if you need to wait, check `isConnected()` first.
---
### `load(track)`
Loads a new media item on the receiver. The receiver starts playing automatically after this call; always follow with `setVolume()` then `play()` or `pause()` to set the correct volume and play state before the browser starts decoding.
```javascript
cast.load({
name: 'Episode 3.mp4', // displayed in receiver toolbar
type: 'video', // 'audio' | 'video' | 'photo'
src: streamUrl, // full URL the receiver's