微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

未处理的承诺拒绝:NotAllowedError:用户代理不允许请求

如何解决未处理的承诺拒绝:NotAllowedError:用户代理不允许请求

用户第一次输入时,我试图在 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 举报,一经查实,本站将立刻删除。