Получить метаданные файла в Angular

Как получить время продолжительности видео/аудио в угловой форме, когда выбран файл для загрузки?

Я получаю каждый файл в формате .html с помощью этого прослушивателя событий:

(change)="fileSelected($event)"

и в файле .ts есть этот код:

attachedFile;

fileSelected($event) {
  this.attachedFile = <File>event.target.files[0]

  var video = document.createElement('video');
  video.preload = 'metadata';

  video.onloadedmetadata = function() {
    window.URL.revokeObjectURL(video.src);
    var duration = video.duration; // here we have duration time but couldn't use out of this scope
  }

  video.src = URL.createObjectURL(this.attachedFile);

  //not available in fileSelected function scope
  console.log(duration); //undefined
}
var foo = duration; // undefined

person Hama Bohel    schedule 07.08.2019    source источник
comment
Код машинописного текста имеет неблокирующий характер. Итак, я думаю, что к моменту вызова функции video.onloadedmetadata функция console.log(duration) уже выполняется.   -  person Eeshwar Ankathi    schedule 07.08.2019
comment
но в результате этого он недоступен из функции fileSelected и может использовать только console.log рядом с объявлением   -  person Hama Bohel    schedule 07.08.2019
comment
Вы получаете ошибку undefined, а не Reference Error, что означает, что здесь применяется тот же оператор, к тому времени, когда продолжительность установлена, остальная часть кода выполняется.   -  person Eeshwar Ankathi    schedule 07.08.2019
comment
Это правильно, но нет способа разделить их, и они выполняются одновременно   -  person Hama Bohel    schedule 07.08.2019


Ответы (1)


Относится к check-video-length-on-upload-angular. Вот как.

<input type="file" (change)="onVideoChange($event)" accept="video/mp4,video/x-m4v,video/*">
<!-- Preview Section that gets the video metadata for us -->
<video #video autoplay (loadedmetadata)="getDuration($event)" *ngIf="videoUrl" controls class="EYOsld Xpig"
    [attr.src]="videoUrl"> </video>

В разделе компонентов...

import { Component, OnInit } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
import { FormGroup, Validators, FormBuilder } from '@angular/forms';
export class VideoComponent implements OnInit {
    videoForm: FormGroup;
    previewVideoUrl;

    constructor(
        private formBuilder: FormBuilder,
        private domSanitizer: DomSanitizer
    ) { }
    ngOnInit() {
        this.videoForm = this.formBuilder.group({
            'video': [null, [Validators.required, Validators.nullValidator]],
            'duration': [null, [Validators.required, Validators.nullValidator]],
        });

    }

    onVideoChange(event) {
        const file = event.target.files[0];
        this.videoForm.get('video').setValue(file);
        const previewVideoFiles = event.target.files;
        if (previewVideoFiles && previewVideoFiles[0]) {
            this.videoUrl = this.domSanitizer.bypassSecurityTrustUrl(URL.createObjectURL(files[0]));
        }
    }

    getDuration(e) {
        const duration = e.target.duration;
        `
        Note the duration is in seconds, hence if you want the duration in minutes the you would have
        /*
            duration = duration / 60 ;
        */
        If you would want to duration in hours, 
        /* 
            duration = (duration / 60) / 60
        */
        `
        this.videoForm.get('duration').setValue(duration);
    }
}



// Final note remember to import `ReactiveFormsModule` from '@angular/forms' and add ReactiveFormsModule in imports section in app.module.ts
person lwairore    schedule 14.12.2019