Angular 7 - Trying to create a preview of an audio file before upload

别说谁变了你拦得住时间么 提交于 2019-12-24 03:22:49

问题


My desired result is to create a preview of an audio file before it is uploaded to the server. However after file input, nothing happens. A file is not dynamically added to the aduio tag, nor do I receive any errors. The console shows that the file was loaded. Any help would be greatly appreciated!

My component html has~

<audio controls #figAudio>
  <source [src]="audSrc" type="audio/ogg">
  <source [src]="audSrc" type="audio/mpeg">
  <source [src]="audSrc" type="audio/wav">
</audio>
<input type="file" (change)="audFileSelected($event)">

My component ts file has ~

audSrc: SafeUrl;

constructor (
  private sanitize: DomSanitizer
) {}

sanitizeUrl(url: string) {
  return this.sanitize.bypassSecurityTrustUrl(url);
}

audFileSelected(event: any) {
  console.log(event.target.files[0]);
  if (event.target.files && event.target.files[0]) {
    const reader = new FileReader();
    reader.readAsDataURL(event.target.files[0]);
    reader.onload = (evt: any) => {
      this.audSrc = evt.target.result;
        };
    }
}

回答1:


Okay, I solved the issue. Instead of using FileReader I just use a URL object. I then use a custom pipe to sanitize my audio url.

component.ts file~

@ViewChild('figAudio') figAudio: ElementRef; // audio tag reference
audSrc = 'path/to/default/sound.mpeg';

audFileSelected(event: any) {
  if (event.target.files && event.target.files[0]) {
    const audSrc = URL.createObjectURL(event.target.files[0]);
    this.figAudio.nativeElement.src = this.audSrc;
  }
}

component.html file~

<audio #figAudio>
  <source [src]="audSrc | sanitizerUrl" type="audio/ogg">
  <source [src]="audSrc | sanitizerUrl" type="audio/mpeg">
  <source [src]="audSrc | sanitizerUrl" type="audio/wav">
</audio>

sanitize-url.pipe.ts ~

@Pipe({
  name: 'sanitizerUrl'
})
export class SanitizerUrlPipe implements PipeTransform {

  constructor (
    private sanitize: DomSanitizer
  ) {}

  transform(value: string): SafeUrl {
    return this.sanitize.bypassSecurityTrustUrl(value);
  }
}


来源:https://stackoverflow.com/questions/53946212/angular-7-trying-to-create-a-preview-of-an-audio-file-before-upload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!