Azure-Samples / communication-services-ios-quickstarts

Sample code for Azure Communication Services iOS quickstarts
MIT License
12 stars 24 forks source link

Video not streamed when switch the camera from front to back or Vice versa #85

Open sachinpatel3 opened 4 months ago

sachinpatel3 commented 4 months ago

Here is the function for toggle camera:- public func toggleCamera() { do { // Access device manager cameras directly, catching any potential nil let availableCameras = try sharedState.deviceManager!.cameras

      // Define scaling mode for the preview view
      let scalingMode: ScalingMode = .crop

      // Initialize local video streams if nil
      if (sharedState.localVideoStreams == nil) {
          sharedState.localVideoStreams = [LocalVideoStream]()
      }
    if(sharedState.isUsingFrontCamera){
      // Create and append local video stream from first available camera
      let localVideoStream = LocalVideoStream(camera: availableCameras.first{ $0.cameraFacing == .back }!)
      sharedState.localVideoStreams!.append(localVideoStream)

      // Create preview renderer and view for the local video stream
      sharedState.previewRenderer = try VideoStreamRenderer(localVideoStream: sharedState.localVideoStreams!.first!)
      sharedState.previewView = try sharedState.previewRenderer!.createView(withOptions: CreateViewOptions(scalingMode: scalingMode))
      sharedState.isUsingFrontCamera.toggle()
    }else{
      let localVideoStream = LocalVideoStream(camera: availableCameras.first{ $0.cameraFacing == .front }!)
      sharedState.localVideoStreams!.append(localVideoStream)

      // Create preview renderer and view for the local video stream
      sharedState.previewRenderer = try VideoStreamRenderer(localVideoStream: sharedState.localVideoStreams!.first!)
      sharedState.previewView = try sharedState.previewRenderer!.createView(withOptions: CreateViewOptions(scalingMode: scalingMode))
      sharedState.isUsingFrontCamera.toggle()
    }

      // Start video stream with error handling
      sharedState.call!.startVideo(stream: sharedState.localVideoStreams!.first!) { (error) in
          if (error != nil) {
              sharedState.alertMessage = "Could not share video"
              sharedState.showAlert = true
          }
          else {
              sharedState.sendingLocalVideo = true
          }
      }
  } catch let error {
      // Handle any errors caught during the process
      sharedState.alertMessage = "Error toggling camera: \(error.localizedDescription)"
      sharedState.showAlert = true
  }

}