switchCamera static method

Future<bool> switchCamera(
  1. MediaStreamTrack track, [
  2. String? deviceId,
  3. MediaStream? stream
])

For web implementation, make sure to pass the target deviceId

Implementation

static Future<bool> switchCamera(MediaStreamTrack track,
    [String? deviceId, MediaStream? stream]) async {
  if (track.kind != 'video') {
    throw 'The is not a video track => $track';
  }

  if (!kIsWeb) {
    return WebRTC.invokeMethod(
      'mediaStreamTrackSwitchCamera',
      <String, dynamic>{'trackId': track.id},
    ).then((value) => value ?? false);
  }

  if (deviceId == null) throw 'You need to specify the deviceId';
  if (stream == null) throw 'You need to specify the stream';

  var cams = await cameras;
  if (!cams.any((e) => e.deviceId == deviceId)) {
    throw 'The provided deviceId is not available, make sure to retreive the deviceId from Helper.cammeras()';
  }

  // stop only video tracks
  // so that we can recapture video track
  stream.getVideoTracks().forEach((track) {
    track.stop();
    stream.removeTrack(track);
  });

  var mediaConstraints = {
    'audio': false, // NO need to capture audio again
    'video': {'deviceId': deviceId}
  };

  var newStream = await openCamera(mediaConstraints);
  var newCamTrack = newStream.getVideoTracks()[0];

  await stream.addTrack(newCamTrack, addToNative: true);

  return Future.value(true);
}