javascript - 如何修复错误错误:未捕获(承诺):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()
我将如何解决它?
解决方案
你的问题是因为你没有音频源,我修改了你的 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() 承诺保存在变量中很有用,在其他情况下,您可以直接使用它(我在示例中的操作方式)
推荐阅读
- c++ - 被调试线程的CPU核数
- python - python函数调用的访问变量?
- java - 制作无法关闭的Android应用
- swiftui - iOS14 SwiftUI 如何在 TabView 上禁用滚动
- .net - .NET Core - 如何使用身份服务器从控制器重定向到身份服务器登录
- php - Laravel:无法从表单上传信息
- html - html textarea中的新行
- swift - FirebaseCrashlytics/run:构建应用程序时没有此类文件或目录错误 - swift
- angular - 在 Brave 和 Incognito 中,MSAL 没有用户登录错误
- spring-boot - 休眠延迟初始化对象的 Spring Data Rest HAL 响应格式问题