【发布时间】:2020-07-16 05:35:25
【问题描述】:
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>
重新加载页面时如何修复 ERROR 错误:未捕获(承诺中):NotAllowedError: play()?
因为当我运行应用程序时,音频可以正常工作,但是当我尝试重新加载警报/通知时,警报/通知可以正常工作,但音频无法正常工作,导致出现错误。这是 ERROR Error: Uncaught (in promise): NotAllowedError: play()
我将如何解决它?
【问题讨论】:
-
当你在.then()中做AUDIO.play()时,它会返回一个Promise,你也需要在里面做一个.then和.catch
-
我添加了一个问题。然后我尝试播放()音频它同样的错误
ERROR Error: Uncaught (in promise): NotAllowedError: play() -
@OscarVelandia 我已经更新了我的代码。
-
我的意思是playPromise.then(() => { AUDIO.play() .then(console.log) // 这里可以看到响应。 }) .catch(console.log ); // 这里你可以看到错误。如果您看到您的 playPromise 与 AUDIO.play() 相同。如果你能在 codebox 中做一个例子,我可以以最好的方式帮助你。
-
这是正确的吗?
notificationAudio.play().then(err => console.log(err));或notificationAudio.play().then(err => console.log(playPromise));
标签: javascript angular typescript html5-audio