Once you have connected to a session, you can subscribe to streams in the session. When you subscribe to a stream, its video stream appears in the client page and its audio is played.
This topic includes the following sections:
To subscribe to all streams in the session, add an OTSubscriber object as a chile of the OTSession object:
<OTSession
apiKey="the API key"
sessionId="the session ID"
token="the token">
<OTSubscriber/>
</OTSession>
After the client connects to the session, the OTSubscriber object adds views for subscriber videos when other clients streams become available in the session.
The OTSubscriber object dispatches a connected
event when a subscriber successfully starts streaming. It dispatches an error
event if there is an error subscribing. Set an eventHandlers
prop of the OTSubscriber component, and set the connected
and error
properties of that object to callback functions:
<OTSubscriber
eventHandlers={{
connected: () => {
console.log('The subscriber started streaming.');
},
error: () => {
console.log('The subscriber failed.');
}
}}/>
Pass in a properties
prop for the OTSubscriber object to set properties for all subscribers:
<OTSubscriber
properties={{
subscribeToAudio: true,
subscribeToVideo: false,
subscribeToCaptions: true,
preferredResolution: 30,
preferredFrameRate: '352x288',
audioVolume: 50,
}}/>
Alternately, you can set the streamProperties
OTSubscriber prop to a object that defines individual settings for each stream. The object's properties are a key-value pairs, with the stream ID as the key, and the value set to an object with subscribeToAudio
, subscribeToVideo
, subscribeToCaptions
, preferredResolution
, preferredFrameRate
, and audioVolume
overrides for the subscriber to the stream:
class App extends Component {
constructor(props) {
super(props);
this.state = {
streamProperties: {},
};
this.subscriberProperties = {
subscribeToAudio: false,
subscribeToVideo: true,
subscribeToCaptions: false,
};
this.sessionEventHandlers = {
streamCreated: event => {
const streamProperties = {...this.state.streamProperties, [event.streamId]: {
subscribeToAudio: true,
subscribeToVideo: false,
style: {
width: 400,
height: 300,
},
}};
this.setState({ streamProperties });
},
};
}
render() {
return (
<OTSession apiKey="your-api-key" sessionId="your-session-id" token="your-session-token" eventHandlers={this.sessionEventHandlers}>
<OTSubscriber
properties={this.subscriberProperties}
eventHandlers={this.subscriberEventHandlers}
style={{ height: 100, width: 100 }}
streamProperties={this.state.streamProperties}
/>
</OTSession>
);
}
}
The properties
object includes the following properties:
subscribeToAudio
— (Boolean) Whether to subscribe to audio.subscribeToVideo
— (Boolean) Whether to subscribe to video.subscribeToCaptions
— (Boolean) Whether to subscribe to captions. See Live captions -- React NativepreferredResolution
— (String) The preferred resolution. See Setting the preferred frame rate and resolution.preferredFrameRate
— (Number) The preferred frame rate. See Setting the preferred frame rate and resolution.audioVolume
— (Number) The audio volume, from 0 to 100.By default, the OTSubscriber adds child views for subscriber videos. However, you can add a render function to add the OTSubscriber object to add subcribers. The function is passed an array of stream IDs:
import { OTSubscriberView, OTSubscriber } from 'opentok-react-native'
// Render method:
<OTSubscriber>
{streamIds => {
if (streamIds.length === 0) {
return null;
}
return streamIds.map(streamId => {
return (
<OTSubscriberView
streamId={streamId}
key={streamId}
style={{
width: 200,
height: 150,
}}
/>
);
});
}}
</OTSubscriber>
Use the OTSubscriberView component to render individual streams. The OTSubscriberView component inherits the props (such as style
) from the React Native View component. Additionally, it has a streamId
prop that you use to pass in the stream ID for the subscriber's stream.
Note: The streamProperties
prop of the OTSubscriber object is ignored if these child OTSubscriberView components are added.
The OTSession object dispatches a streamCreated
event when a new stream (other than your own) is created in a session. A stream is created when a client publishes a stream to the session. The streamCreated
event is also dispatched for each existing stream in the session when you first connect.
<OTSession
eventHandlers={{
streamCreated: () => {
console.log('Stream created -- stream ID:', event.streamId);
}
}}/>
The streamCreated
event object includes details about the stream, including connection data, video source type ('camera' or 'screen'), and more. You may use this information to determine how streams are arranged (or which streams to include) when using a
Subscribers are automatically destroyed when the publishing client stops publishing. To stop subscribing to an ongoing stream, unmount the corresponding OTSubscriberView component from the OTSubscriber component. See Custom rendering of subscribers.
When a stream, other than your own, leaves a session the OTSession object dispatches a streamDestroyed
event:
<OTSession
eventHandlers={{
streamDestroyed: (event) => {
console.log('Stream destroyed -- stream ID:', event.streamId);
}
}}/>
The streamDestroyed
event object has the following properties that define the stream:
connection
An object corresponding to the connection that is publishing the stream. This includes a data
property that includes connection data (if any was set) for the client.
creationTime
The timestamp (a number) for the creation of the stream. This value is calculated in milliseconds.
hasAudio
(Boolean) Whether the stream has audio. This property can change if the publisher turns on or off audio. When this occurs, the OTSession object dispatches a streamPropertyChanged
event.
hasVideo
(Boolean) Whether the stream has video.
name
(String) The name of the stream, if one was set when the stream was published.
videoDimensions
This object has two properties: width
and height
. Both are numbers. The width
property is the width of the encoded stream; the height
property is the height of the encoded stream. (These are independent of the actual width of Publisher and Subscriber objects corresponding to the stream.) This property can change if a stream published from a mobile device resizes, based on a change in the device orientation.
videoType
The type of video: either "camera" or "screen". A "screen" video uses screen sharing on the publisher as the video source. This property can change if the published stream changes froma camera to a screen-sharing video source. For more information, seeScreen sharing — React Native.The hasAudio
, hasVideo
, videoDimensions
, and videoType
properties can change (for example, when the publisher turns on or off video). When this occurs, the OTSession object dispatches a streamPropertyChanged
event.
If a client drops a connection to a subscribed stream (for example, due to a drop in network connectivity in either client), it will attempt to automatically reconnect to the stream. When the stream is dropped and the client tries to reconnect, the OTSubscriber object dispatches a disconnected
event. When the stream is restored, the OTSubscriber object dispatches a connected
event. If the client cannot restore the stream, the OTSubscriber object dispatches a destroyed
event.
In response to these events, your application can (optionally) display user interface notifications indicating the temporary disconnection, reconnection, and destroyed states:
<OTSubscriber
eventHandlers={{
disconnected: (event) => {
console.log('stream disconnected -- stream ID:', event.streamId);
// Display a user interface notification.
},
connected: (event) => {
console.log('stream connected -- stream ID:', event.streamId);
// Adjust user interface.
},
destroyed: (event) => {
console.log('stream destroyed -- stream ID:', event.streamId);
// Adjust user interface.
}
}}/>
When subscribing to a stream that uses the scalable video feature, you can set the preferred frame rate and preferred resolution for the stream the subscribing client receives from the OpenTok Media Router.
<OTSubscriber
properties={{
preferredFrameRate: 7,
preferredResolution: '352x288',
}}/>
preferredFrameRate
— The preferred frame rate, in frames per second. Valid values are are 30, 15, 7, and 1. Leave this undefined to remove the preferred frame rate, and the client will use the highest frame rate available.
preferredResolution
— The preferred resolution. Valid values are "1280x720", "640x480", and "352x288". Leave this undefined to remove the preferred resolution, and the client will use the highest frame rate available.
When a subscriber's video is disabled, the OTSubscriber object dispatches a videoDisabled
event:
<OTSubscriber
eventHandlers={{
videoDisabled: (event) => {
console.log('stream video disabled -- stream ID:', event.streamId);
// Display a user interface notification.
},
}}/>
When the OpenTok Media Router disables the video of a subscriber, you may want to adjust the user interface related to the subscriber.
The reason
property of the videoDisabled
event object defines the reason the video was disabled. This can be set to one of the following values:
"PublisherPropertyChanged"
— The publisher stopped publishing video.
"QualityChanged"
— The OpenTok Media Router stopped sending video to the subscriber based on stream quality changes. This feature of the OpenTok Media Router has a subscriber drop the video stream when connectivity degrades. (The subscriber continues to receive the audio stream, if there is one.)
Before sending this event, when the subscriber's stream quality deteriorates to a level that is low enough that the video stream is at risk of being disabled, the OTSubscriber objet dispatches a videoDisableWarning
event.
If connectivity improves to support video again, the OTSubscriber object dispatches a videoEnabled
event, and the subscriber resumes receiving video.
This feature is only available in sessions that use the OpenTok Media Router (sessions with the media mode set to routed), not in sessions with the media mode set to relayed.
When you publish a stream, you can prevent it from having its video disabled due to streamquality. Set audioFallbackEnabled
to false
in the properties
prop pass into the OTPublisher component.
"SubscriberPropertyChanged"
— The subscriber started or stopped subscribing to video, by setting subscribeToVideo
to false in the properties
prop passed into the OTSubscriber component.
"CodecNotSupported"
— The subscriber stopped subscribing to video due to an incompatible codec (see the Video codecs developer guide).
The OTSubscriber object dispatches videoEnabled
event when video resumes:
The reason
property of the videoEnabled event object defines the reason the video was enabled. This can be set to one of the following values:
"PublisherPropertyChanged"
— The publisher resumed publishing video.
"QualityChanged"
— The OpenTok Media Router resumed sending video to the subscriber based on stream quality changes. This feature of the OpenTok Media Router has a subscriber drop the video stream when connectivity degrades and then resume the video stream if the stream quality improves.
This feature is only available in sessions that use the OpenTok Media Router (sessions with the media mode set to routed), not in sessions with the media mode set to relayed.
"SubscriberPropertyChanged"
— The subscriber started or stopped subscribing to video, by setting subscribeToVideo
to false in the properties
prop passed into the OTSubscriber component.
"CodecNotSupported" — The subscriber video was enabled after a codec change from an incompatible codec (see the Video codecs developer guide).
A stream's video dimensions can change if a stream published from a mobile device resizes, based on a change in the device orientation. It can also occur if the video source is a screen-sharing window and the user publishing the stream resizes the window that is the source for the stream.
When a stream's video dimensions change, the Session object dispatches a streamPropertyChanged event, with the changedProperty
property of the event set to "videoDemensions"
.
To get audio and video statistics for subscribers, add event handlers for the audioNetworkStats
and videoNetworkStats
event dispatched by the OTSubscriber. These provide information about the subscriber's stream, including the following:
<OTSubscriber
eventHandlers={{
audioNetworkStats: event => {
console.log('subscriber audioNetworkStats event', event);
},
videoNetworkStats: event => {
console.log('subscriber videoNetworkStats event', event);
},
}}
/>
To get more detailed stream statics, use the Subscriber.getRtcStatsReport() method of the OTSubscriber object. It returns a promise that, on success, resolves with a JSON representation of an RtcStatsReport object for the subscribed stream:
<OTSubscriber
eventHandlers={{
connected: event => {
setTimeout(() => {
this.subscriber.getRtcStatsReport();
}, 4000);
},
rtcStatsReport: event => {
console.log('subscriber rtcStatsReport event', event);
},
}}
/>