dam*_*mon 5 javascript audio ios reactjs
我的问题的沙盒演示:https://codesandbox.io/s/jolly-fermat-j23w9
我正在尝试在我的 React 网站上实现一项功能,用户单击一个元素,然后播放音频。
在桌面上,这工作正常。但在 iOS 设备上,我遇到了“未处理的拒绝(NotAllowedError)”。此错误通常是由iOS 设备上自动播放媒体引起的。但是,在这种情况下,用户必须单击该元素才能启动音频,因此不应发生此错误。
我的怀疑是,由于组件在状态更改时重新渲染,React 不知道用户必须与站点交互才能触发音频。
这是基本代码:
// audio playing function, found on this stackoverflow question:
// /sf/ask/3338044181/
const useAudio = url => {
const [audio] = useState(new Audio(url));
const [playing, setPlaying] = useState(false);
const toggle = () => setPlaying(!playing);
useEffect(() => {
playing ? audio.play() : audio.pause();
}, [playing]);
return [playing, toggle];
};
// url of audio is passed in as prop from App.js
const PlayAudio = ({ url }) => {
const [playing, toggle] = useAudio(url);
return (
<>
<PlayButton onClick={toggle}>{playing ? "Pause" : "Play"}</PlayButton>
</>
);
};
Run Code Online (Sandbox Code Playgroud)
在 iPhone 上使用 Safari、Chrome 和 Firefox 浏览器进行测试。
同样,可以在此处找到完整的工作演示,您需要检查 iOS 设备才能看到错误: https: //codesandbox.io/s/jolly-fermat-j23w9
任何帮助表示赞赏。
使用您的代码创建示例,但使用另一种方法:
<audio ref....>
Run Code Online (Sandbox Code Playgroud)
https://codesandbox.io/s/elegant-black-c0jr8
| 归档时间: |
|
| 查看次数: |
2192 次 |
| 最近记录: |