Joseph Vargas
Joseph Vargas

Reputation: 792

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

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

Upvotes: 2

Views: 3603

Answers (1)

Joseph Vargas
Joseph Vargas

Reputation: 792

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

Upvotes: 5

Related Questions