0

I am trying to do a check to see if the video I uploaded is longer than 30s, but cannot get the example I need. This is the code I have so far where I check the size and some other things:

readVideoUrl(event: any) {
      this.videoFile = [];
        const eventObj: MSInputMethodContext = <MSInputMethodContext> event;
        const target: HTMLInputElement = <HTMLInputElement> eventObj.target;
        const files: FileList = target.files;
        if (files) {
            this.videoFile.push(files[0]);
            this.videoModel.name = files[0].name;
        }


        if (event.target.files && event.target.files[0]) {
            let reader = new FileReader();

            reader.onload = (event: ProgressEvent) => {
                this.videoUrl = (<FileReader>event.target).result;
            };

            reader.readAsDataURL(event.target.files[0]);
        }

        const FileSize = files[0].size / 1024 / 1024; // in MB
        if (FileSize > 50) {
            this.videoSizeError = true;
        } else {
            this.videoSizeError = false;
        }

        this.videoModel.file = event.target.value;
        this.videoModel.name = event.target.files[0].name;
    }

Any suggestions?

Nemanja G
  • 1,760
  • 6
  • 29
  • 48
  • The FileReader itself can’t give you that info - it has no concept of a specific file type “video”. I guess you will have to load this video into an actual `video` element first, so that you can then use its methods to check for the video length. – misorude Oct 10 '18 at 12:41
  • @misorude I have video element already, I just pass the url to it, how can I retrieve the length from it? – Nemanja G Oct 10 '18 at 12:43
  • Type something trivial such as “html5 video get length” into Google and find out …? – misorude Oct 10 '18 at 12:45

1 Answers1

8

I'd add an invisible video player and set its source then get the duration from that:

HTML:

<input type="file" (change)="readVideoUrl($event)">

<p *ngIf="videoSizeError">Too big</p>

<video #video style="display: none;" *ngIf="videoUrl" width="320" height="240" controls [attr.src]="videoUrl" (loadedmetadata)="getDuration($event)">
</video>

TS:

import { Component } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  videoUrl;
  videoSizeError;

  constructor(private sanitizer: DomSanitizer) { }

  readVideoUrl(event: any) {
    const files = event.target.files;
    if (files && files[0]) {
      this.videoUrl = this.sanitizer.bypassSecurityTrustUrl(URL.createObjectURL(files[0]));
    }
  }

  getDuration(e) {
    const duration = e.target.duration;
    this.videoSizeError = duration > 30;
  }
}

working code's link

Nima Hakimi
  • 1,382
  • 1
  • 8
  • 23