首页 > 解决方案 > 使用 React.js 循环音频列表

问题描述

我正在尝试自学 React.js,但我对音频列表的循环方式有点困惑。

我尝试构建一个可以播放声音的应用程序,但我遇到了无法循环播放音频列表的问题。目前,应用程序随机获取声音列表中的一个元素并播放,我仍然希望应用程序继续随机播放列表中的声音,直到我单击停止按钮。但目前,它只能重复一次,我不明白为什么。我做了谷歌搜索,但我找不到任何解决方案。有人可以帮我吗?

这是我的尝试:

class PlaySound extends React.Component {
    constructor(props) {
      super(props);

      this.state = {
        play: false
      };
      // first link: 1s , second link: 7s   
      this.urls = ["https://actions.google.com/sounds/v1/water/air_woosh_underwater.ogg", "https://actions.google.com/sounds/v1/water/drinking_from_water_fountain.ogg"];
      this.audio = new Audio(this.urls[0]);
      this.audio.addEventListener('ended', this.updateAudio.bind(this), false);
      this.togglePlay = this.togglePlay.bind(this);
    }

    updateAudio() {
        const random = Math.floor(Math.random() * this.urls.length) + 0;
        console.log(random)
        this.audio = new Audio(this.urls[random]);
        this.audio.play()
    }

    togglePlay() {
      const wasPlaying = this.state.play;
      this.setState({
        play: !wasPlaying
      });

      if (wasPlaying) {
        this.audio.pause();
      } else {
        this.audio.play()
      }
    }

    render() {
      return (
        <div>
          <button
            id="audioBtn"
            onClick={this.togglePlay}> {this.state.play ? "Pause" : "Play"}
          </button>
        </div>
      );
    }
  }

  ReactDOM.render(<PlaySound />, document.getElementById("root"));

标签: reactjsloopsaudio

解决方案


好像您正在this.audio使用 updateAudio 方法进行重置。我认为你应该'ended'再次绑定你的 eventListener。

检查下面的代码

updateAudio() {
 const random = Math.floor(Math.random() * this.urls.length) + 0;
 console.log(random)
 // added below line.
 this.audio = new Audio(this.urls[random]);
 this.audio.addEventListener('ended', this.updateAudio.bind(this), false);
 this.audio.play()
}

推荐阅读