我需要通过用户单击预览图标来播放声音。
这是我的 html 代码:
<audio controls>
<source [src]="fileSource" type="audio/mp3">
</audio>
这是 ts 代码:
fileSource: any;
ngOnInit(): void {
if (typeof this.data.src === 'number') {
this.getImageFromService();
}
}
createImageFromBlob(image: Blob): void {
const reader = new FileReader();
reader.addEventListener('load', () => {
this.fileSource = reader.result;
}, false);
if (image) {
reader.readAsDataURL(image);
}
}
getImageFromService(): void {
this.isLoading = true;
this.postFileService.downloadFile(this.data.src).subscribe(data => {
this.createImageFromBlob(data);
this.isLoading = false;
}, error => {
this.isLoading = false;
console.log(error);
});
}
这是我的服务:
downloadFile(id: number): Observable<Blob> {
const URL = `${this.appConfig.apiEndpoint + '/PostFileContent/DownloadFile/' + id}`;
return this.http.get(URL, { responseType: 'blob' });
}
现在我的问题是这样的:
我需要在单击预览图标时打开模式对话框并播放音频。
当我单击预览图标时,文件已下载但无法播放。
有什么问题吗?我该如何解决这个问题???
最佳答案
以下代码将用于自动播放从后端(node.js)检索的音频文件。
angular.html
<audio controls>
<source type="audio/mpeg" [src]="fileSource" >
</audio>
angualr.ts
// mention your backend url directly here like below
fileSource:any = 'http://localhost:1234/getAudioFile';
节点后端代码
app.use('/getAudioFile',function(req,res,next){
// i stored sample mp3 file in my local directory
var filePath = path1.join(__dirname, './sample.mp3');
var stat = fileSystem.statSync(filePath);
res.writeHead(200, {
'Content-Type': 'audio/mpeg',
'Content-Length': stat.size
});
var readStream = fileSystem.createReadStream(filePath);
// We replaced all the event handlers with a simple call to readStream.pipe()
readStream.pipe(res);
// res.send("this is audio ");
next();
});
注意::确保您直接从后端获取音频文件(无论是node还是java)。
关于javascript - 在 Angular 8 中下载并播放流音频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58039576/