[英]how to turn off the loop of audio loop in reactjs?
I tried to build an alert app and it can notify twice. 我试图构建一个警报应用程序,它可以通知两次。
First notification just play the sound once and second play repeats of the sound. 第一次通知仅播放一次声音,第二次重复播放声音。
I import the sound use the webpack
: 我使用
webpack
导入声音:
import audio from '../file/sound.mp3';
and call this file in my constructor 并在我的构造函数中调用此文件
constructor(props){
super(props);
this.state={
timeIsComing: false,
timeIsUp: false,
}
this.audio = new Audio(audio);
}
the function of in the timeInterval
timeInterval
的功能
countDown(){
if(timeIsComing){
this.audio.play();
}
if(timeIsUp){
this.audio.addEventListener('ended', this.playSounds.bind(this), false);
this.audio.play();
}
}
the playSounds()
function: playSounds()
函数:
playSounds(){
this.audio.currentTime = 0;
this.audio.play();
}
I set a reset function to initialize the alert. 我设置了一个重置功能来初始化警报。
But when I reset and count the timer second times, the state of timeIsComing
become true
and the sound will play in unlimited loop. 但是当我第二次重置计时器并计时时,
timeIsComing
的状态变为true
,并且声音将无限循环播放。
my reset function: 我的重置功能:
reset(){
this.setState({timeIsComing: false, timeIsUp: false});
this.audio.removeEventListener('ended', this.playSounds.bind(this), false);
this.audio.pause();
}
Is there way to turn off the repeats? 有没有办法关闭重复?
UPDATE UPDATE
Demo At CodePen two times alert App Demo 演示在CodePen 两次提醒App演示
I believe the issue is that you're passing different functions in your addEventListener/removeEventListener calls. 我相信问题在于您在addEventListener / removeEventListener调用中传递了不同的函数。
You should bind your this.playSounds
function like this : 您应该像这样绑定
this.playSounds
函数:
constructor(props){
super(props);
this.state={
timeIsComing: false,
timeIsUp: false,
}
this.playSounds = this.playSounds.bind(this);
this.audio = new Audio(audio);
}
and then you can just do : 然后你可以做:
this.audio.removeEventListener('ended', this.playSounds, false);
same thing for addEventListener
. addEventListener
。 Binding in the attach/remove of the event will create a new function. 绑定事件的附加/删除将创建一个新功能。 So when you try to remove it, it will not find that function.
因此,当您尝试删除它时,它将找不到该功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.