Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Camera not working in iPhone in Web Browsers in Blazor WASM

We have written the below code in blazor WASM where we are trying to capture image of user on web browser.

Index.razor

 <div class="v-canvas">
     <video id="videoFeed" width="320" height="240" />
     <canvas class="d-none" id="currentFrame" width="320" height="240" />
 </div>
  <button @onclick="CaptureFrame">
       <span>Capture</span>
   </button>


@code {
 protected override async Task OnInitializedAsync()
 {
     await JSRuntime.InvokeVoidAsync("startVideo", "videoFeed");

 }

 private async Task CaptureFrame()
 {
     await JSRuntime.InvokeAsync<String>("getFrame", "videoFeed", "currentFrame",DotNetObjectReference.Create(this));
 }

}

 [JSInvokable]
 public async Task ProcessImage(string imageString)
 {

    //Some logic

 }

Javascript Code

function startVideo(src) {
    if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
        navigator.mediaDevices.getUserMedia({ video: true }).then(function (stream) {
            let video = document.getElementById(src);
            if ("srcObject" in video) {
                video.srcObject = stream;
            } else {
                video.src = window.URL.createObjectURL(stream);
                video.webkitMatchesSelector.src = window.URL.createObjectURL(stream);
            }
            video.onloadedmetadata = function (e) {
                video.play();
                video.webkitMatchesSelector.play();
                Play(src);
            };

            //mirror image
            video.style.webkitTransform = "scaleX(-1)";
            video.style.transform = "scaleX(-1)";
        });
    }
}


function getFrame(src, dest, dotNetHelper) {
    let video = document.getElementById(src);
    let canvas = document.getElementById(dest);
    canvas.getContext('2d').drawImage(video, 0, 0, 320, 240);

    let dataUrl = canvas.toDataURL("image/jpeg");
    dotNetHelper.invokeMethodAsync('ProcessImage', dataUrl);
}

The above solution is been published on IIS and tested on multiple devices.

This works perfectly on iPad, MacBook, Windows laptops and android phones. For iPhones in Safari/Chrome, the video does not loads in browsers at all, even after camera permission is given.

The Reference of this code is taken from - https://wellsb.com/csharp/aspnet/blazor-webcam-capture

like image 672
raw_hitt Avatar asked Nov 16 '25 07:11

raw_hitt


1 Answers

Found a solution after a long time.

I had to add the below attributes in the video tag in js file.

    let video = document.getElementById(src);
    video.setAttribute('autoplay', '');
    video.setAttribute('muted', '');
    video.setAttribute('playsinline', '');

Hope this helps others :)

like image 104
raw_hitt Avatar answered Nov 17 '25 20:11

raw_hitt