Как исправить ошибку DOMException в Google Chrome? - PullRequest
0 голосов
/ 13 мая 2019

Я работаю со звуками в браузерной игре. Я написал звуковой менеджер. все отлично работает, но не в гугл хроме. Я обработал ошибку «uncaught (in обещание) Domexception», после того, как звуки были воспроизведены в 50 процентах случаев, в других случаях он возвращает ошибку DOMException. В чем может быть проблема?

export class AudioFile{
    private audio: HTMLAudioElement;
    private fileMP3: string;
    private fileOGG: string;
    private volume = 1;
    private loop = false;
    constructor(MP3:string, OGG:string) {
        this.audio = new Audio();
        this.fileMP3 = MP3;
        this.fileOGG = OGG;
        this.audio.canPlayType('audio/mpeg') ? this.audio.src = this.fileMP3 : this.audio.src = this.fileOGG;
        this.audio.load();
        this.audio.volume = this.volume;
        this.audio.loop = this.loop;
    }
    public play() {
        this.audio.currentTime = 0;
        const playPromise = this.audio.play();
        if (playPromise !== undefined) {
            playPromise.then(_ => {
            })
            .catch(error => {
                console.log(error);
            });
        }
    }
    public stop() {
        this.audio.pause();
    }
}
``````````````sound manager`````````````
export class SoundManager {
    private sounds = new Map();
    private static _soundManager: SoundManager;
    constructor(){
        if (SoundManager._soundManager) {
            throw new Error("Instantiation failed: "+
            "use Singleton.getInstance() instead of new.");
        }
        SoundManager._soundManager = this;
    }
    public static get instance(): SoundManager {
        if (this._soundManager)
            return this._soundManager;
        else
            return this._soundManager = new SoundManager();
    }
    preload() {
        const pathMP3 = SoundConfig.PATHMP3;
        const pathOGG = SoundConfig.PATHOGG;
        for (const item in SoundConfig.SOUNDS) {
            const name = SoundConfig.SOUNDS[item].NAME;
            this.sounds.set(name, new AudioFile(pathMP3 + name + '.mp3', pathOGG + name + '.ogg'));
        }
    }
    getSound(id: string): AudioFile {
        return this.sounds.get(id);
    }
}

1 Ответ

1 голос
/ 14 мая 2019

Спасибо, потраченный.

error: DOMException code: 0 message: "play() failed because the user didn't interact with the document first.

Игра проходит через iframe, и мне нужно было добавить политику функций для автоигры.

<iframe src="..." allow="autoplay">

статья , которая помогла мне в решении проблемы

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...