【问题标题】:Howler JS & React AudioContext console warningHowler JS & React AudioContext 控制台警告
【发布时间】:2022-01-04 16:02:03
【问题描述】:

我在一个简单的组件中使用 howler.js,它呈现一个按钮来播放音频文件

在控制台中我收到以下警告:

AudioContext error

“AudioContext 不允许启动。它必须在页面上的用户手势后恢复(或创建)。

声音播放没有任何问题,但我无法摆脱这个警告

根据警告需要执行手势,我认为单击按钮会提供该手势

这是组件中的代码:

import React from "react";
import { useState } from "react";
import { Howl } from "howler";

export const Sound = ({ name, path }) => {
  const [playing, setPlaying] = useState(false);

  const Sound = new Howl({
    src: [path],
  });

  const playSound = () => {
    setPlaying(true);
    Sound.play();
  };

  return (
    <div>
      <button onClick={() => playSound()}>{name}</button>
      <p>{playing ? "playing" : "Not playing"}</p>
    </div>
  );
};

我检查了多个问题/论坛/github问题,但找不到解决方案

感谢您提供有关此问题出现原因的任何帮助或信息!

谢谢!

【问题讨论】:

    标签: javascript reactjs google-chrome audiocontext howler.js


    【解决方案1】:

    我认为在这种情况下您可以忽略此警告。它被触发是因为 howler.js 预先创建了一个 AudioContext。

    https://github.com/goldfire/howler.js/blob/4537db79b3dca9ed490ee22cbb17048d4cba7316/src/howler.core.js#L2517

    调用play()时AudioContext会自动恢复。

    https://github.com/goldfire/howler.js/blob/4537db79b3dca9ed490ee22cbb17048d4cba7316/src/howler.core.js#L822

    因此,警告很烦人,但已经被 howler.js 的作者处理了。但如果你真的想摆脱警告,你可以在播放之前懒惰地初始化 Sound 变量。

    // ...
    let Sound;
    
    const playSound = () => {
        setPlaying(true);
    
        if (Sound === undefined) {
            Sound = new Howl({
                src: [path]
            });
        }
    
        Sound.play();
    };
    // ...
    

    这应该会使警告消失。

    【讨论】:

      猜你喜欢
      • 2020-02-16
      • 2019-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-26
      • 2020-04-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多