问题描述
当用户第一次输入时,我试图在 Iphone X 上的 safari 上播放音频,但我不断收到错误
Unhandled Promise Rejection: NotAllowedError: The request is not allowed by the user agent or the platform in the current context,posible because the user denied permission
当我尝试播放背景声音时,在以下行之后出现错误。
this.getAudio("assets/sounds/soundtrack.mp3").tryPlay();
我什至制作了自己的声音类,以便在获得许可之前防止播放声音。这对声音效果非常有用。但它不适用于背景声音。第一次用户输入后如何播放背景声音?
import App from "../../../app";
import * as createjs from "createjs-module";
export default class AudioManager {
private map: Map<string,Sound>;
private pointerDownHandler: () => void;
constructor(sounds:Map<string,HTMLAudioElement>) {
this.map = new Map<string,Sound>();
sounds.forEach((value,key) => {
this.map.set(key,new Sound(key,value));
value.pause();
});
this.pointerDownHandler = this.requestAudioPermission;
window.addEventListener("pointerdown",this.pointerDownHandler);
}
requestAudioPermission = async () => {
const AudioContext = window.AudioContext || window.webkitaudiocontext;
const ctx = new AudioContext();
await ctx.resume();
this.map.forEach((value) => {
value.givePermissionToPlay();
});
this.getAudio("assets/sounds/soundtrack.mp3").tryPlay();
window.removeEventListener("pointerdown",this.pointerDownHandler);
};
getAudio(key: string): Sound {
return this.map.get(key) as Sound;
}
fadeMusic(sound: Sound,to: number) {
sound.fade(to);
}
mute() {
this.map.forEach((map) => {
map.setMuted(true);
});
}
unmute() {
this.map.forEach((map) => {
map.setMuted(false);
});
}
}
export class Sound {
private name: string;
private audioElement: HTMLAudioElement;
private hasPermissionToPlay = false;
public get muted(): boolean {
return this.audioElement.muted;
}
constructor(name: string,audioElement: HTMLAudioElement) {
this.name = name;
this.audioElement = audioElement;
}
tryPlay() {
if (this.hasPermissionToPlay) {
this.audioElement.play();
console.log(this.name);
}
}
pause() {
this.audioElement.pause();
}
setMuted(mute: boolean) {
this.audioElement.muted = mute;
}
setVolume(volume: number) {
this.audioElement.volume = volume;
}
setCurrentTime(time: number) {
this.audioElement.currentTime = time;
}
setLoop(loop: boolean) {
this.audioElement.loop = loop;
}
fade(to: number) {
createjs.Tween.get(this.audioElement).to({ volume: to },500);
}
givePermissionToPlay() {
this.hasPermissionToPlay = true;
}
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)