gpt4 book ai didi

reactjs - 无法在 Reactjs 中暂停音频

转载 作者:行者123 更新时间:2023-12-04 00:55:14 25 4
gpt4 key购买 nike

我已经关注了其他提出类似问题的帖子,但他们没有提供解决方案。
我无法在我的 React Hook 中暂停音频。
这是我的 react 钩子(Hook):

import React, { useState } from "react";

export default (App = props => {
const [audioStatus, changeAudioStatus] = useState(false);
const audio = new Audio(
"https://mcdn.podbean.com/mf/web/xm5ngf/The_Challenge_Chronicles_-_Episode_48_7ys6e.mp3"
);
audio.load();

const startAudio = () => {
audio.play();

changeAudioStatus(true);
};

const pauseAudio = () => {
console.log("here");
audio.pause();
changeAudioStatus(false);
};

return (
<>
{audioStatus ? (
<button onClick={pauseAudio}>pause</button>
) : (
<button onClick={startAudio}>start</button>
)}
</>
);
我还创建了一个沙箱: https://codesandbox.io/s/great-gagarin-v0vi1

最佳答案

您可以使用 audio标记,并传递 ref使用react,以便它知道正在使用什么元素。
working example

export default (App = props => {
const [audioStatus, changeAudioStatus] = useState(false);
const myRef = useRef();

const startAudio = () => {
myRef.current.play();

changeAudioStatus(true);
};

const pauseAudio = () => {
console.log("here");
myRef.current.pause();
changeAudioStatus(false);
};

return (
<>
<audio
ref={myRef}
src="https://mcdn.podbean.com/mf/web/xm5ngf/The_Challenge_Chronicles_-_Episode_48_7ys6e.mp3"
/>
{audioStatus ? (
<button onClick={pauseAudio}>pause</button>
) : (
<button onClick={startAudio}>start</button>
)}
</>
);
});

关于reactjs - 无法在 Reactjs 中暂停音频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63003690/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com