React 设置 audio.ended 侦听器
React set audio.ended listener
正如我在这里研究的一些答案,在 React 应用程序中添加音频的好方法如下:
import music from '~assets'
class Audio extends Component {
state = {...}
audio = new Audio(music)
...
this.audio.play()
this.audio.pause()
...
}
实施后,我意识到除非暂停,否则我无法将其设置为自动重播。 有没有办法在不切换到显式创建 <audio />
标签的情况下使用当前设置来做到这一点?
PS。正如我所见,主要问题是我无法找到附加 onended
侦听器或检查 this.audio.ended
的正确位置的方法。
解决方案比我预期的要简单得多。
在我用来调用 this.audio.play()
的函数中,我将 loop
属性 添加到音频
play = () => {
if (this.audio === null) {
this.audio = new Audio(music);
}
this.audio.loop = true; //this one
this.setState({ play: true, pause: false });
this.audio.play();
};
正如我在这里研究的一些答案,在 React 应用程序中添加音频的好方法如下:
import music from '~assets'
class Audio extends Component {
state = {...}
audio = new Audio(music)
...
this.audio.play()
this.audio.pause()
...
}
实施后,我意识到除非暂停,否则我无法将其设置为自动重播。 有没有办法在不切换到显式创建 <audio />
标签的情况下使用当前设置来做到这一点?
PS。正如我所见,主要问题是我无法找到附加 onended
侦听器或检查 this.audio.ended
的正确位置的方法。
解决方案比我预期的要简单得多。
在我用来调用 this.audio.play()
的函数中,我将 loop
属性 添加到音频
play = () => {
if (this.audio === null) {
this.audio = new Audio(music);
}
this.audio.loop = true; //this one
this.setState({ play: true, pause: false });
this.audio.play();
};