Skip to main content

AirPlay

AirPlay support is implemented as a plugin, meaning it must be installed and enabled separately.

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 useAirPlay 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 {useAirPlay, useAirPlayState} from '@castlabs/react-native-prestoplay-airplay';

// Wrapped with the PlayerProvider
const MyComponent = () => {
const airPlay = useAirPlay();
const airPlayState = useAirPlayState();

if (airPlayState === AirPlayState.Available) {
return (<Button onPress={() => airPlay.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 airPlay = player.getExtension<AirPlayExtension>(AirPlayExtension)
airPlay.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);
});