问题
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