javascript - 在 Angular 8 中下载并播放流音频

标签 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' });
}

现在我的问题是这样的:

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

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

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

最佳答案

以下代码将用于自动播放从后端(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/

相关文章:

angular - #something ="ngModel"的简单英语

javascript - 如何从全局函数访问 Angular 分量函数 - 请兼容 IE11

typescript - 在 Electron 的预加载脚本中使用 typescript

Angular 2 : Why do I need classes like Hero. ts?

javascript - 将 XSLT 变量设置为 JavaScript 变量?

angular - 如何使用 forkjoin 返回 Angular 中两个独立 API 调用的组合响应

javascript - Angular组件多实例绑定(bind)输入问题

javascript - 如何使用 "name = xxx"进行验证

javascript - 完美的触摸就绪、iPad 兼容和内容滑动就绪网站的框架

javascript - jQuery Domino Like slider 插件