我正在尝试在react js中创建一个小应用程序,以播放和暂停音乐/声音。歌曲结束后,我希望曲目从头开始。此刻,歌曲第一次结束会重新开始播放,但是一旦结束就不会再播放。
我还有一个“停止”按钮,该按钮在第一次按下时会停止,但是随后将不再起作用。有人能帮忙吗?我确定我只是在做傻事
代码:
import React, { useState } from "react";
function Controls(props) {
const audio = new Audio(props.source);
const [isPlaying, playStatus] = useState(false);
let interval;
function playState() {
console.log(isPlaying);
console.log("here: Playing");
audio.currentTime = 0;
audio.play();
playStatus(true);
startTimer(props.duration);
}
function pauseState() {
console.log(isPlaying);
console.log("here 1");
audio.currentTime = 0;
audio.pause();
clearInterval(interval);
playStatus(false);
}
function startTimer(seconds) {
let currentPlayTime = 0;
if (currentPlayTime === 0) {
interval = setInterval(function() {
currentPlayTime++;
if (currentPlayTime === seconds) {
playState();
clearInterval(interval);
}
}, 1000);
} else {
alert("Running");
}
}
return (
<div>
<button className="Button" onClick={playState}>
Play
</button>
<button className="Button" onClick={pauseState}>
Stop
</button>
<audio id="myAudio" src={props.source} />
</div>
);
}
export default Controls;
链接到代码沙箱:
https://codesandbox.io/s/soundsappppppp-oe4gf?file=/src/components/Controls.jsx:0-1172
谢谢