Having trouble getting Edge browser to identify embedded blob as a valid source URL within a video tag

Having trouble using a blob as the source for a video file.

Works well on Chrome and Safari, but facing issues on Edge.

This code is written in TypeScript with Angular 7. On Edge mobile, it seems like a broken link is displayed.

private initVideoFromBlob(blob: Blob) {
  const edBlob = new Blob([blob], { type: 'video/mp4' });
  const url = URL.createObjectURL(edBlob);
  this.videoSrc = this.sanitizer.bypassSecurityTrustResourceUrl(url);
}

Tried another approach, but encountered the same problem:

private initVideoFromBlob(blob: Blob) {
  let url: any;
  const edBlob = new Blob([blob], { type: 'video/mp4' });
  if (window.navigator.msSaveOrOpenBlob) {
    url = window.navigator.msSaveOrOpenBlob(edBlob);
  } else {
    url = (URL || webkitURL).createObjectURL(edBlob);
  }
  this.videoSrc = this.sanitizer.bypassSecurityTrustResourceUrl(url);
}

My HTML:

<video controls>
  <source *ngIf="videoSrc" [src]="videoSrc" type="video/mp4" />
</video>

Edit:

Attempted converting blob to dataURL following DarticCode's suggestion, but still facing the same issue.

private async initVideoFromBlob(blob: Blob) {
  let url: string | boolean;
  const edBlob = new Blob([blob], { type: 'video/mp4' });
  if (/Edge\//.test(navigator.userAgent) || /EdgA\//.test(navigator.userAgent)) {
    const promise = new Promise((resolve, reject) => {
      const fr = new FileReader();
      fr.onload = x => resolve(fr.result);
      fr.readAsDataURL(edBlob);
    });

    url = await promise;
  } else {
    url = (URL || webkitURL).createObjectURL(edBlob);
  }
  this.videoSrc = this.sanitizer.bypassSecurityTrustResourceUrl(url);
}

Answer №1

There is a bug that will be addressed in the next release. You'll need to convert the blob to a data URI.

//**Converting dataURL to blob**
function dataURLtoBlob(dataurl) {
    var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    while(n--){
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], {type:mime});
}

//**Converting blob to dataURL**
function blobToDataURL(blob, callback) {
    var a = new FileReader();
    a.onload = function(e) {callback(e.target.result);}
    a.readAsDataURL(blob);
}

//test:                    blob URL \/
var blob = dataURLtoBlob('data:text/plain;base64,YWFhYWFhYQ==');
blobToDataURL(blob, function(dataurl){
    console.log(dataurl);
    
    //dataurl is a variable here that allows you to work with blob as dataurl
});

Answer №2

I conducted a test with a local video file and found that it performs well on Edge browser. Since I didn't have a pre-existing blob URL, I decided to first convert the local video file into a blob. See the code snippet below for reference:

<video controls>
    <source id="videoSrc" type="video/mp4" >
</video>

<script>
    var xhr = new XMLHttpRequest();
    xhr.responseType = 'blob';

    xhr.onload = function () {

        var reader = new FileReader();

        reader.onloadend = function () {

            var byteCharacters = atob(reader.result.slice(reader.result.indexOf(',') + 1));

            var byteNumbers = new Array(byteCharacters.length);

            for (var i = 0; i < byteCharacters.length; i++) {

                byteNumbers[i] = byteCharacters.charCodeAt(i);

            }

            var byteArray = new Uint8Array(byteNumbers);
            var blob = new Blob([byteArray], { type: 'video/mp4' });
            var url = URL.createObjectURL(blob);

            document.getElementById('videoSrc').src = url;

        }

        reader.readAsDataURL(xhr.response);

    };

    xhr.open('GET', 'video/test.mp4');
    xhr.send();
</script>

You can view the result here. If you encounter any issues with the above method, consider creating a minimal sample to troubleshoot the problem.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adding a fresh attribute to MongoDB using push model

I wrote a basic script that calculates the number of documents for a specific user and assigns it to externalUser.totalIcons. However, when I try to execute it, the model is not saved and the new property is not added to the database. My question is: wher ...

"Prisma vs. Supabase: A Comparison of Image Uploading

I am encountering an issue with adding image URLs to the Prisma database. I have successfully uploaded multiple images from an input file to Supabase storage, but when I try to add their URLs to the database, I receive an error regarding property compatibi ...

Issue with React TSX component in NextJs 14.0.4: Local MP3 files cannot be played, only external online MP3 files work

I have created a component that wraps around HTML audio and source tags. It functions perfectly when playing mp3 files from an external source, like this sound clip . However, it returns a GET 404 error when trying to access local mp3 files. Can anyone exp ...

Create a PDF document utilizing Angular Ignite UI for Angular

Currently working with Angular TypeScript 12, I have successfully integrated Angular Ignite UI grid. However, I am in need of a way to export my grid into a PDF format using Igx-Grid. Does Igx-Grid support PDF exporting? If not, are there any alternative ...

Is it possible to automatically generate a discriminated union for every interface within a given namespace?

Currently utilizing TypeScript version 2.5, but willing to switch to 2.6 if necessary. In my code base, there exists a namespace containing a variety of interfaces: export namespace Interfaces { export interface One { kind: "One" } e ...

Using Angular's setTimeout() function with an external lambda that includes a parameter

My goal is to tackle two issues at once: 1) using setTimeout( #action#, timeMillis) with #action# as a lambda 2) supplying the lambda with a parameter. The common method of setTimeout( ()=>{ #callback# }, timeMillis) works flawlessly when extracting () ...

Utilizing Angular 2 Animations with the ngOnInit Lifecycle Hook

Suppose I envision a sleek navigation bar gracefully dropping down from the top of the browser once my app/website loads. Is it feasible to achieve this fluid motion using component animations metadata? Currently, I have managed to make it function as des ...

Angular and Node version discrepancies causing problems

This particular CLI version is designed to work with Angular versions ^11.0.0-next || >=11.0.0 <12.0.0, however an Angular version of 13.0.0 was detected instead. If you need assistance with updating your Angular framework, please refer to the follo ...

Angular2's Dynamic Forms

When attempting to incorporate FormsArray into my Project using ReactiveFormsModule, I encountered an error message stating: Cannot find control with unspecified name attribute. Is it possible to add FormsArray in template driven forms? Here is the code ...

Tips for preventing duplicate imports in Sass with the @use rule in Webpack

My sass modules have the ability to import each other as shown in the examples below: // LinearLayout.scss @mixin LinearLayout { ... } linear-layout { @include LinearLayout; } // ScrollView.scss @use "LinearLayout" as *; @mixin ScrollView { ...

Can you please provide an explanation on the functioning of Dependency Injection in Nestjs?

I have been delving into Nest.js and incorporating it into my project structure. Additionally, I have integrated TypeORM into the mix. The concept of Dependency Injection in Nest.js has me feeling a bit perplexed. Project Structure |-APP_MODULE |-app.co ...

What is the best way to utilize a tsconfig "alias path" to import an @ngModule along with other definitions?

Repository Link: https://github.com/andreElrico/mono-repo-test Stackblitz Example: https://stackblitz.com/github/andreElrico/mono-repo-test (noop; only to navigate smoothly) Assume the structure below: root/ ├── projects/ │ ├── app1 │ ...

Utilizing Angular routing with Module Federation

I am currently involved in a module federation project. mfe1: ParentApp mfe2: childApp1 mfe3: childApp2 mfe4: childApp3(parent of ChildApp1) Each of the child applications, including childApp1, childApp2, and childApp3, have their own routing modules tha ...

Watchable: Yield the outcome of a Promise as long as watching continues

I am looking to create a function in Angular and TypeScript that will return an Observable for subscription. This Observable should emit the result of a Promise every three seconds. Currently, I have a function that returns a Promise, but I need it to ret ...

Is it possible to detect individual key value modifications in Firestore using Angular?

getUserEventSummaryE(userId) { return docData(doc(this.firestore, `/user/${userId}/event_summary/current/`), {idField : 'playing_summary'}). pipe(distinctUntilChanged((prev, curr) => _.isEqual(prev, curr))); } getUserEventSummaryE functio ...

What is the best way to connect an object to an array using ngFor in Angular?

It has been noticed that in Angular, the current variable does not align with the available options. Even though the object { question: 'q3', answer: '' } exists in data.questions, it may not be a direct match. Is there a method to en ...

Leveraging Observables in an Angular 2 component to broadcast data to multiple components

Is it possible to utilize Observables in components and which other components can subscribe to them? BugListComponent - The component is injected in the boot.ts file where all services are loaded (where bootstrap is located) import {Subject, BehaviorSub ...

"Experience the power of Angular with 15 incredibly dynamic components utilizing the compileModuleAndAllComponentsAsync function

Currently, I am in the process of transitioning a project from Angular 8 to version 15. One of the key features of the application is dynamic product cards, where the template for these cards is arbitrary HTML loaded from the server and unknown during deve ...

What is the best way to create Jest unit tests for an Angular Component without using TestBed?

I'm diving into the world of Jest testing and feeling lost as to why my tests keep failing. If you have any recommendations for videos or articles that focus on writing Jest unit tests for Angular components and services without using "TestBed," plea ...

Tips for dynamically altering the bound variable in Angular

Most people understand the concept of interpolation and how to interpolate a single variable with ease. However, what if we need to dynamically switch between two different variables? Let's say we have two class properties: public first: string = &ap ...