Suggestions

close search

Add Messaging, Voice, and Authentication to your apps with Vonage Communications APIs

Visit the Vonage API Developer Portal

Subscribing to streams — React Native

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:

Subscribing to a stream

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.');
  }
}}/>

Setting stream properties

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:

Custom rendering of subscribers

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.

Detecting when streams are created in a session

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

Unsubscribing from a stream

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.

Detecting when streams leave a session

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:

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.

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.

Automatic reconnection

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.
    }
  }}/>

Setting the preferred frame rate and resolution

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',
  }}/>

Detecting when a subscriber's video is disabled

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:

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:

Detecting when a stream's video dimensions change

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".

Getting stream statistics

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);
    },
  }}
/>