【问题标题】:Angular 7 - Trying to create a preview of an audio file before uploadAngular 7 - 尝试在上传之前创建音频文件的预览
【发布时间】:2019-05-25 13:14:49
【问题描述】:

我想要的结果是在将音频文件上传到服务器之前创建它的预览。然而,文件输入后,什么也没有发生。文件不会动态添加到 aduio 标签,我也不会收到任何错误。控制台显示文件已加载。任何帮助将不胜感激!

我的组件html有~

<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)">

我的组件 ts 文件有 ~

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;
        };
    }
}

【问题讨论】:

    标签: angular typescript angular7


    【解决方案1】:

    好的,我解决了这个问题。我不使用 FileReader,而是使用 URL 对象。然后我使用自定义管道来清理我的音频网址。

    component.ts 文件~

    @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 文件~

    <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);
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-12
      • 2019-03-25
      • 1970-01-01
      • 2011-05-26
      相关资源
      最近更新 更多