[英]how to turn off the loop of audio loop in reactjs?
我試圖構建一個警報應用程序,它可以通知兩次。
第一次通知僅播放一次聲音,第二次重復播放聲音。
我使用webpack
導入聲音:
import audio from '../file/sound.mp3';
並在我的構造函數中調用此文件
constructor(props){
super(props);
this.state={
timeIsComing: false,
timeIsUp: false,
}
this.audio = new Audio(audio);
}
timeInterval
的功能
countDown(){
if(timeIsComing){
this.audio.play();
}
if(timeIsUp){
this.audio.addEventListener('ended', this.playSounds.bind(this), false);
this.audio.play();
}
}
playSounds()
函數:
playSounds(){
this.audio.currentTime = 0;
this.audio.play();
}
我設置了一個重置功能來初始化警報。
但是當我第二次重置計時器並計時時, timeIsComing
的狀態變為true
,並且聲音將無限循環播放。
我的重置功能:
reset(){
this.setState({timeIsComing: false, timeIsUp: false});
this.audio.removeEventListener('ended', this.playSounds.bind(this), false);
this.audio.pause();
}
有沒有辦法關閉重復?
UPDATE
演示在CodePen 兩次提醒App演示
我相信問題在於您在addEventListener / removeEventListener調用中傳遞了不同的函數。
您應該像這樣綁定this.playSounds
函數:
constructor(props){
super(props);
this.state={
timeIsComing: false,
timeIsUp: false,
}
this.playSounds = this.playSounds.bind(this);
this.audio = new Audio(audio);
}
然后你可以做:
this.audio.removeEventListener('ended', this.playSounds, false);
addEventListener
。 綁定事件的附加/刪除將創建一個新功能。 因此,當您嘗試刪除它時,它將找不到該功能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.