You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

点击播放声音按钮时应用抛出FsReadStream相关TypeError并崩溃

问题场景

点击按钮尝试播放声音时,应用抛出错误并直接关闭。

错误信息

TypeError: Cannot set property closed of #<Readable> which has only a getter at FsReadStream.close

相关代码

组件方法

playSound(): void {
  let audio = new Audio(); 
  audio.src = './assets/notification/notification.wav'; 
  audio.load(); 
  audio.play(); 
}

模板按钮

<button (click)="playSound()"> 
  <mat-icon>trash</mat-icon>
</button>

解决方案

  1. 提升Audio实例作用域
    把Audio实例定义为组件类的成员属性,避免函数执行完毕后被垃圾回收,导致流处理异常:
// 组件类中定义
private audio: Audio;

playSound(): void {
  this.audio = this.audio || new Audio();
  this.audio.src = './assets/notification/notification.wav';
  this.audio.play();
}
  1. 移除多余的load()调用
    现代浏览器设置src后会自动触发加载流程,手动调用load()可能在Node.js/Electron这类混合环境中引发流处理冲突,直接删除即可。

  2. 添加错误捕获避免应用崩溃
    给play()方法添加错误监听,即使播放失败也不会导致应用直接关闭:

playSound(): void {
  this.audio = this.audio || new Audio();
  this.audio.src = './assets/notification/notification.wav';
  this.audio.play().catch(err => {
    console.error('音频播放失败:', err);
  });
}
  1. 验证文件路径正确性
    确认./assets/notification/notification.wav路径是否正确,比如在Angular项目中,assets文件夹需配置在angular.json的assets数组内,确保构建后文件能被正确访问。

内容的提问来源于stack exchange,提问作者Lindomar Souza Dias

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 08:22:44