下载并播放Angle 8流音频

时间:2019-09-21 10:54:30

标签: javascript angular typescript

我需要在用户单击预览图标的情况下播放声音。

这是我的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' });
}

现在我的问题是:

我需要在单击预览图标时打开模式对话框并播放音频。

当我单击预览图标时,文件已下载但无法播放。

是什么问题?我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

以下代码可用于自动播放从后端(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();
});

注意 ::确保直接从后端获取音频文件(与节点或Java无关)。