AirPlay

The AirPlay plugin lets viewers stream playback to AirPlay devices. It’s a plugin, so you install and enable it separately.

Note

On web, AirPlay works only with HLS streams played by Safari’s native player (preferNativeHlsOnSafari: true).

Setup

First, install the @castlabs/react-native-prestoplay-airplay package:

npm install @castlabs/react-native-prestoplay-airplay

Once the plugin is installed, enable it when initializing the SDK, by passing the AirPlayPlugin class. For example:

import { Sdk } from "@castlabs/react-native-prestoplay";
import { AirPlayPlugin } from "@castlabs/react-native-prestoplay-airplay";

Sdk.initialize({
  licenseKey: {
    /* Valid license here */
  },
  plugins: [AirPlayPlugin],
});

iOS

Initialize an audio session in the ./ios/<APP_NAME>/AppDelegate.mm file:

#import <AVFoundation/AVFoundation.h>

//...

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  //...
  [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
  [[AVAudioSession sharedInstance] setActive:true error:nil];

  return [super application:application didFinishLaunchingWithOptions:launchOptions];
}

Finally, enable background audio by adding the following snippet to the ./ios/<APP_NAME>/Info.plist file:

<key>UIBackgroundModes</key>
<array>
  <string>audio</string>
</array>

Usage

Within a component wrapped by the PlayerProvider, the AirPlay extension can be accessed using the useAirPlayExtension hook. Furthermore, the AirPlay state can be accessed through the useAirPlayState hook. For example:

import React from "react";
import { Button } from "react-native";
import { AirPlayState } from "@castlabs/react-native-prestoplay";
import {
  useAirPlayExtension,
  useAirPlayState,
} from "@castlabs/react-native-prestoplay-airplay";

// Wrapped with the PlayerProvider
const MyComponent = () => {
  const airPlayExtension = useAirPlayExtension();
  const airPlayState = useAirPlayState();

  if (airPlayState === AirPlayState.Available) {
    return (
      <Button onPress={() => airPlayExtension.showCastDialog()}>AirPlay</Button>
    );
  } else {
    return null;
  }
};

Alternatively, the AirPlay extension can be directly accessed through a Player instance. For example:

import { AirPlayExtension } from "@castlabs/react-native-prestoplay-airplay";
const airPlayExtension = player.getExtension(AirPlayExtension);
airPlayExtension.showCastDialog();

…and the AirPlay state changes can be observed by registering an event listener on a Player instance. For example:

import {
  AirPlayStateChangedDetails,
  Event,
  EventType,
} from "@castlabs/react-native-prestoplay";
player.addEventListener(EventType.AirPlayStateChanged, (event: Event) => {
  const details = event.details as AirPlayStateChangedDetails;
  console.log("AirPlay state:", details.currentState);
});
Next topic: Chromecast
Previous topic: Playlist