iOS v-0.0.10 / Android v-0.0.3

Import

To integrate the Truvideo SDK, include the following platform-specific imports:

#if IOS
using UIKit;
using Foundation;
using TruvideoCameraiOS;
#endif

#if ANDROID
using Application = Android.App.Application;
using TruVideoCameraAndroidBinding;
using JsonSerializer = System.Text.Json.JsonSerializer;
using DotnetCameraLib = TruVideoCameraAndroid.DotnetCameraTruvideo;
#endif

Async Callback Wrapper

For handling asynchronous callbacks in Android, use the following method:

#if ANDROID
private Task<T> ExecuteCameraCallbackAsync<T>(Action<CameraCallback> action)
{
    var tcs = new TaskCompletionSource<T>();

    action.Invoke(new CameraCallback(
        success => MainThread.BeginInvokeOnMainThread(() =>
            tcs.TrySetResult((T)Convert.ChangeType(success, typeof(T)))),
        failure => MainThread.BeginInvokeOnMainThread(() => tcs.TrySetException(new Exception(failure)))
    ));

    return tcs.Task;
}
#endif

#if IOS
private Task<T> ExecuteCallbackAsync<T>(Action<Action<string, NSError>> nativeCall) {
    var tcs = new TaskCompletionSource<T>();
    nativeCall((nsResult, error) => {
        if (error != null)
        {
            tcs.SetException(new Exception(error.LocalizedDescription));
        }
        else {
            // Convert NSString to string
            string result = nsResult.ToString();
            tcs.TrySetResult((T)Convert.ChangeType(result, typeof(T)));
           // tcs.SetResult(result);
        }
    });
    return tcs.Task;
}
#endif

This function executes image-related actions asynchronously and ensures results are processed on the main thread.

Camera Initialization

To initialize the camera, import the TruvideoSdkCamera module into the controller first. Next, customize the camera settings by utilizing TruvideoSdkCameraConfiguration with appropriate parameters to tailor it to your specific requirements.

Once the configuration is complete, proceed to display the camera view for capturing photos and clips.

#if ANDROID
SubscribeToCameraEvents();
var config = new ModeTypeConfig();
config.RawType = ModeType.VideoAndPicture;
config.VideoCount = null;
config.PictureCount = null;
config.VideoDuration = null;
var orientation = OrientationMode.Portrait;
var mode = FlashMode.Off;
var lensType = LensType.Back;
var cameraResult = await ExecuteCameraCallbackAsync<string>(cb => DotnetCameraLib.ShowCamera(Application.Context, lensType, mode, orientation, "",config, cb));
var captures = JsonSerializer.Deserialize<List<TruvideoSdkCameraMedia>>(cameraResult);
_cameraList = new List<string>();

if (captures != null)
    foreach (var capture in captures)
    {
        Console.WriteLine(
            $"FileRahul: {capture.FilePath}, Resolution: {capture.Resolution.Width}x{capture.Resolution.Height}");
        _cameraList.Add(capture.FilePath);
    }

LogTextEditor.Text = "Selected media paths: " + string.Join(", ", _cameraList);
    
#endif

#if IOS
var lensFacing = LensType.Back;
var flashMode = FlashMode.Off;
var orientation = OrientationMode.Portrait;
var mode = ModeTypeConfig.VideoAndPicture(null, null, null);
SubscribeToCameraEvents();
void ShowCameraHandler(NSArray<NSString> paths)
{
    MainThread.BeginInvokeOnMainThread(() =>
    {
        if (paths.Count > 0)
        {
            LogTextEditor.Text += "Selected media paths:\n" + paths + "\n";
            _selectedMedia = paths;
        }
        else
        {
            LogTextEditor.Text += "No selected media\n";
        }
    });
}
var currentViewController = UIApplication.SharedApplication.KeyWindow.RootViewController;
TruvideoCamera.Shared.ShowCamera(lensFacing, flashMode, orientation, "", mode, currentViewController,
ShowCameraHandler);
#endif

Note The Camera module can run into errors if used by itself because it depends on a shared component. The Video module also uses this same component, and to avoid conflicts, TruVideo manages it within the Video module. This means:

  • If you use only the Camera module → errors may occur.

  • If you use the Camera and Video modules together → everything works smoothly, since the shared component is managed centrally

Entities

Camera information

TruvideoSdkCameraInformation defines a structure holding information about available camera devices within the TruvideoSDK. It contains references to both front and back cameras, providing details such as device ID, lens facing direction, supported resolutions, flash availability, tap-to-focus capability, and sensor orientation. Developers can utilize this data to dynamically configure camera options and tailor the user experience accordingly.

public class TruvideoSdkCameraMedia{    
    [JsonPropertyName("cameraLensFacing")]    
    public string CameraLensFacing { get; set; }    
    
    [JsonPropertyName("createdAt")]    
    public long CreatedAt { get; set; }  // Timestamp 
       
    [JsonPropertyName("duration")]    
    public int Duration { get; set; }    
    
    [JsonPropertyName("filePath")]    
    public string FilePath { get; set; }    
    
    [JsonPropertyName("id")]    
    public string Id { get; set; }    
    
    [JsonPropertyName("resolution")]    
    public TruvideoSdkCameraResolution Resolution { get; set; }    
    
    [JsonPropertyName("rotation")]    
    public string Rotation { get; set; }    
    
    [JsonPropertyName("type")]    
    public string Type { get; set; }
 }

Camera Resolution

TruvideoSdkCameraResolution is a class representing a specific resolution supported by a camera device. It includes attributes for width and height, allowing developers to ascertain available resolution options when configuring camera settings within their applications.

public class TruvideoSdkCameraResolution{    
    [JsonPropertyName("width")]    
    public int Width { get; set; }    
    
    [JsonPropertyName("height")]
    public int Height { get; set; }
}

Lens Facing

TruvideoSdkCameraLensFacing enum represents the two possible directions of a camera lens: back or front.

public enum TruvideoSdkCameraLensFacing{    
    Back = 0,    
    Front = 1
}

Flash Mode

TruvideoSdkCameraFlashMode enum defines two flash modes: off and on, offering developers control over flash functionality during media capture.

public enum TruvideoSdkCameraFlashMode{    
    Off = 0,    
    On = 1
}

Orientation

TruvideoSdkCameraOrientation enum offers four orientation choices: portrait, landscapeLeft, landscapeRight, and portraitReverse, enabling developers to define camera orientation preferences for media capture.

public enum TruvideoSdkCameraOrientation{    
    Portrait = 0,
    LandscapeLeft = 1,    
    LandscapeRight = 2,    
    PortraitReverse = 3
}

Camera Mode

TruvideoSdkCameraMediaMode includes function modes enabling developers to specify whether the camera should capture both video and pictures, only video, or only pictures, respectively.

public enum TruvideoSdkCameraMode{
    Picture = 0,    
    Video = 1,    
    VideoAndPicture = 2
}

Result

The results of TruvideoSDK camera operations, present an array of TruvideoSdkCameraMedia. Each TruvideoSdkCameraMedia object holds essential video attributes like createdAt, filePath, type, cameraLensFacing, rotation, resolution, and duration. Meanwhile, type defines the TruvideoSdkCameraMedia as photo or video as TruvideoSdkCameraMediaType.clip defines video and TruvideoSdkCameraMediaType.photo defines photo. This comprehensive data structure empowers developers to manage captured media seamlessly, facilitating integration and post-processing within their applications.

public class TruvideoSdkCameraMedia{    
    [JsonPropertyName("cameraLensFacing")]    
    public string CameraLensFacing { get; set; }    
    
    [JsonPropertyName("createdAt")]    
    public long CreatedAt { get; set; }  // Timestamp 
       
    [JsonPropertyName("duration")]    
    public int Duration { get; set; }    
    
    [JsonPropertyName("filePath")]    
    public string FilePath { get; set; }    
    
    [JsonPropertyName("id")]    
    public string Id { get; set; }    
    
    [JsonPropertyName("resolution")]    
    public TruvideoSdkCameraResolution Resolution { get; set; }    
    
    [JsonPropertyName("rotation")]    
    public string Rotation { get; set; }    
    
    [JsonPropertyName("type")]    
    public string Type { get; set; }
 }

Camera Events

The SDK communicates various camera-related events to consumers through a publisher that sends TruvideoSdkCameraEvent objects containing details about the event, including its type and creation date.

Event Observer

To observe camera events, consumers can register an observer using the provided Observer class. The observer listens for events and logs details about them.

Example Usage

#if ANDROID
private void SubscribeToCameraEvents()
{
    var nativeService = new DotnetCameraLib();
    var listener = new CameraEventListener();
    // Subscribe to the event
    listener.DataReceived += data =>
    {
        MainThread.BeginInvokeOnMainThread(() => { Console.WriteLine($"Camera Event Data: {data}"); });
    };
    nativeService.SetDataListener(listener);
}
#endif

if IOS
private void SubscribeToCameraEvents()
{
    void ShowCameraEventHandler(NSString path)
    {
        MainThread.BeginInvokeOnMainThread(() =>
        {
            Console.WriteLine("Camera Event: " + path);
        });
    }
    TruvideoCamera.Shared.SubscribeToCameraEvents(ShowCameraEventHandler);
}
public void UpdateProgress(string progressMessage)
{
    MainThread.BeginInvokeOnMainThread(() =>
    {
        // Update UI, e.g., display progress in a Label
        LogTextEditor.Text = progressMessage;
    });
}
#endif

Event Class: TruvideoSdkCameraEvent

This class encapsulates the details of an event, including the event type, associated data, and the event's creation date.

Properties:

  • type: TruvideoSdkCameraEventType The type of event that occurred.

  • data: TruvideoSdkCameraEventData The data associated with the event. This data can vary depending on the event type.

  • createdAt: Date The date and time when the event was created.

public class TruvideoSdkCameraEvent {
    /// Event type
    public TruvideoSdkCameraEventType type;
    public TruvideoSdkCameraEventData data;
}

Event Type Enum: TruvideoSdkCameraEventType

The TruvideoSdkCameraEventType enum defines the types of events that can be emitted by the Camera SDK.

Enum Values:

  • RecordingStarted Triggered when recording starts.

  • RecordingFinished Triggered when recording finishes.

  • RecordingPaused Triggered when recording is paused.

  • RecordingResumed Triggered when recording resumes.

  • PictureTaken Triggered when a picture is taken.

  • CameraFlipped Triggered when the camera is flipped between front and back.

  • ResolutionChanged Triggered when the camera resolution is changed.

  • FlashModeChanged Triggered when the flash mode is changed.

  • ZoomChanged Triggered when the zoom level is changed.

  • MediaDeleted Triggered when media is deleted.

  • MediaDiscard Triggered when media is discarded.

  • Continue Represents an event to continue clicked for saving photos and videos.

Last updated

Was this helpful?