首页 > 解决方案 > 如何修复错误错误:未捕获(承诺):NotAllowedError:以角度重新加载页面时播放()

问题描述

TS

 limitExceed(params: any) {
        params.forEach((data: any) => {
          if (data.percent === 100) {
            this.createNotification('warning', data.sensor, false);
          } else if (data.percent >= 56 && data.percent <= 99.99) {
            this.createNotification('warning', data.sensor, true);
          }
        });
      }
      createNotification(type: string, name: string, types: boolean): void {
            const textColor = '#ff0000';
            const title = 'High humidity!';
            let subtitle: any;

            timer(1000, 300000).subscribe(() => {
              // const subTitle: any;
              if (types) {
                subtitle = name + 'humidity has reached the minimum limit';
              } else {
                subtitle = name + ' humidity has reached the maximum';
              }

              this.notification.config({
                nzPlacement: 'bottomRight',
                nzDuration: 5000,
              });

              this.playWithAudio(type, title, subtitle, textColor);
            });
          }

          playWithAudio(type: string, title: string, subtitle: string, textColor: string) {
            const AUDIO = <HTMLMediaElement>document.getElementById('audio');
            if (AUDIO) {
              AUDIO.muted = true; // temporarily revolves play error on browser
              const playPromise = AUDIO.play();

              this.notification.create(type, title, subtitle, {
                nzStyle: { color: textColor, 'border-left': textColor + ' 5px solid' }
              });

              if (playPromise !== null) {
                playPromise.then(() => { AUDIO.play(); })
.catch(error => { AUDIO.play(); });
              }
            }
          }

HTML

<audio id="audio" hidden>
  <source src="./assets/audio/notif.mp3" type="audio/wav" />
</audio>

如何修复错误错误:未捕获(承诺):NotAllowedError:重新加载页面时播放()?

因为当我运行应用程序时,音频正在工作,但是当我尝试重新加载警报/通知时,警报/通知正在工作,但音频不起作用,导致出现错误。这是 ERROR Error: Uncaught (in promise): NotAllowedError: play()

我将如何解决它?

标签: javascriptangulartypescripthtml5-audio

解决方案


你的问题是因为你没有音频源,我修改了你的 playWithAudio 函数

 playWithAudio() {
    const AUDIO = document.querySelector('audio');

    if (AUDIO) {
      AUDIO.muted = false;
      AUDIO.play();
    }
  }

和你的 HTML

  <audio id="audio" hidden>
    <source src="https://www.kenney.nl/content/3-assets/128-ui-audio/preview.ogg" type="audio/ogg" />
  </audio>

如果您需要在播放文件后执行某些操作,则将 AUDIO.play() 承诺保存在变量中很有用,在其他情况下,您可以直接使用它(我在示例中的操作方式)

这是一个示例https://codesandbox.io/s/silly-colden-yzlno


推荐阅读