我有一个自动播放策略的问题,它完全扰乱了我的自定义布局。
在组件中,有一个默认设置为true的"play“状态来触发自动播放,但在刷新页面后,即使"play”状态设置为true,自动播放也不起作用。现在的问题是,当用户单击play按钮时,状态不会改变,因为它已经是true,解决方案是将其设置为false并再次设置为true,但在此解决方案中,用户必须在图标上单击两次。
有人能帮我吗?也许react-player已经有了触发播放的状态或方法,而我不需要" play“状态来处理播放暂停。
下面是一个简单的示例,说明它是如何工作的
export default function Untitled() {
const playerRef = useRef(null);
const [playing, setPlaying] = useState(true)
return (
<div>
<ReactPlayer
style={{display:"none"}}
controls={false}
playing={playing}
wrapper={"audio"}
progressInterval={200}
config={{
file: {
attributes: {preload: "auto"},
forceAudio:true,
},
}}
/>
<IconButton size="small">
{playerRef && playerRef.current.player.isPlaying ? (
<PauseIcon onClick={() => setPlaying(false)}/>
) : (
<PlayArrowIcon onClick={() => setPlaying(true)}/>
)}
</IconButton>
</div>
)
}
发布于 2021-10-03 14:15:38
这是因为您没有将"ref“传递/赋值给"ReactPlayer”组件。
在这种情况下,ref不是必需的。
export default function Untitled() {
const [playing, setPlaying] = useState(true)
return (
<div>
<ReactPlayer
style={{display:"none"}}
controls={false}
playing={playing}
wrapper={"audio"}
progressInterval={200}
config={{
file: {
attributes: {preload: "auto"},
forceAudio:true,
},
}}
/>
<IconButton size="small">
{playing? (
<PauseIcon onClick={() => setPlaying(false)}/>
) : (
<PlayArrowIcon onClick={() => setPlaying(true)}/>
)}
</IconButton>
</div>
)
}发布于 2021-10-03 21:20:14
解决方案
var promise = document.querySelector('video').play();
if (promise !== undefined) {
promise.then(_ => {
// Autoplay started!
}).catch(error => {
// Autoplay was prevented.
// Show a "Play" button so that user can start playback.
});
}
https://stackoverflow.com/questions/69425243
复制相似问题