reactjs - How can I make audio play for duration of a countdown timer in React?
问题描述
I'm trying to play an audio file for the duration of the timer. The way I current have this structured, the audio file plays for 1 sec and cuts off. How can I make the audio play for the full length of the timer?
I'm using the Countdown Circle Timer project: https://github.com/vydimitrov/react-countdown-circle-timer
I have renderTime
structured so that a start button appears at page load and again at the end of the duration of the timer. Since the play()
function is coupled with the "start" button, the audio only plays for as long as the button is rendered (1 second).
Here's a sandbox: https://codesandbox.io/s/festive-heisenberg-8ejug
import React, { Component } from "react";
import { CountdownCircleTimer } from "react-countdown-circle-timer";
class Timer extends Component {
state = {
isPlaying: false,
durationSeconds: 31,
colors: [["#dadfe0", 1]]
};
startTimer = () => {
this.setState({
isPlaying: true,
colors: [["#ee5253", 0.33], ["#feca57", 0.33], ["#1abc9c"]]
});
const audioEl = document.getElementsByClassName("audio-element")[0]
audioEl.play();
};
resetTimer = () => {
if (this.state.isPlaying === false) {
this.setState({
isPlaying: true,
colors: [["#ee5253", 0.33], ["#feca57", 0.33], ["#1abc9c"]]
});
}
};
render() {
const isPlaying = this.state.isPlaying;
const durationSeconds = this.state.durationSeconds;
const colors = this.state.colors;
const renderTime = value => {
if (value === 0) {
return (
<div className="timer">
<button className="btn-white" onClick={this.resetTimer}>Start</button>
</div>
)
}
if (value === 31) {
return (
<div className="timer">
<button className="btn-white" onClick={this.startTimer}>Start</button>
<audio className="audio-element">
<source src="http://commondatastorage.googleapis.com/codeskulptor-demos/DDR_assets/Sevish_-__nbsp_.mp3"></source>
</audio>
</div>
)
}
if (value <= 30) {
return (
<div className="timer">
<div className="value">{value}</div>
</div>
)
}
};
return (
<CountdownCircleTimer
isPlaying={isPlaying}
size={240}
durationSeconds={durationSeconds}
colors={colors}
trailColor={"#dadfe0"}
strokeWidth={20}
renderTime={renderTime}
onComplete={() => [false]}
/>
);
}
}
export default Timer;
Thanks for any advice you can give!
解决方案
正如我所怀疑的那样,该audio
元素正在被删除。将其添加到此代码块后
if (value <= 30) {
return (
<div className="timer">
<div className="value">{value}</div>
<audio className="audio-element">
<source src="http://commondatastorage.googleapis.com/codeskulptor-demos/DDR_assets/Sevish_-__nbsp_.mp3" />
</audio>
</div>
);
}
你可以看到它一直播放到指定的时间。
推荐阅读
- haskell - 'do' 块中的最后一条语句必须是表达式
- angular - 无法在响应模式下单击 PrimeNg Carousel 内的按钮
- mysql - 如何检查mysql条目是否存在
- python - 创建简单文字冒险游戏时名称未定义错误和缩进错误
- r - 使用 sapply 以预定义的概率进行采样
- php - 我可以将两个 SQL 查询连接在一起以创建一个可以在表中回显的结果吗?
- angular - Angular:如何从不同的模块注入服务
- aws-lambda - 使用他们的 Java SDK 连接到 AWS 需要多长时间?
- python - 如何完全关闭 tkinter 程序?
- nltk - 危害:POSTagger():ArgumentError:参数2:
: 错误类型