我在一個簡單的組件中使用 howler.js,它呈現一個按鈕來播放音頻檔案
在控制臺中,我收到以下警告:
音頻背景關系錯誤
“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問題,但找不到解決方案
感謝您提供有關為什么會出現這種情況的任何幫助或資訊!
謝謝!
uj5u.com熱心網友回復:
我認為在這種情況下您可以忽略此警告。它被觸發是因為 howler.js 預先創建了一個 AudioContext。
https://github.com/goldfire/howler.js/blob/4537db79b3dca9ed490ee22cbb17048d4cba7316/src/howler.core.js#L2517
呼叫 時,AudioContext 會自動恢復play()。
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();
};
// ...
那應該會使警告消失。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/367315.html
標籤:javascript 反应 谷歌浏览器 音频上下文 咆哮.js
