我想在响应中创建一个音乐列表。如何创建它?

时间:2019-07-19 10:47:53

标签: reactjs audio audio-player

我已经在react中创建了“播放暂停”按钮,但是我只能管理一首歌曲。我想列出更多歌曲,并想播放和暂停。我想一次播放一首歌。

我已经尝试过使用音频。

这是我的渲染功能-

n=4000

这是我的构造函数和音频函数-

render() {
        return (
            <div>
                <button getsrc="http://streaming.tdiradio.com:8000/house.mp3" onClick={this.togglePlay}>{this.state.play ? 'Pause' : 'Play'}</button><br /><br />
                <button getsrc="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3" onClick={this.togglePlay}>{this.state.play ? 'Pause' : 'Play'}</button>
                <button getsrc="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-2.mp3" onClick={this.togglePlay}>{this.state.play ? 'Pause' : 'Play'}</button>
                <button getsrc="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-3.mp3" onClick={this.togglePlay}>{this.state.play ? 'Pause' : 'Play'}</button>
            </div>
        );
    }

如何一次播放一首歌。并显示播放的歌曲信息

1 个答案:

答案 0 :(得分:1)

您可以尝试以下代码

state = {
    play: false,
    currentSong: null,
  };

  audio = null;

  togglePlay = (e) => {
    const song = e.target.id;
    if (this.state.currentSong === song) {
      this.state.play ? this.audio.pause() : this.audio.play();
      this.setState({ play: !this.state.play });
    } else {

      if (this.audio) {
        this.audio.pause();
      }

      this.setState({
        currentSong: song,
        play: true,
      });
      this.audio = new Audio(song);
      this.audio.play();
    }
  }

  render() {
    const songs = [
      'http://streaming.tdiradio.com:8000/house.mp3',
      'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3',
      'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-2.mp3',
      'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-3.mp3',
    ];
    return (
      <div>
        {songs.map(song =>
          <div>
            <button id={song} key={song} onClick={this.togglePlay}>
              {this.state.currentSong !== song || !this.state.play ? 'Play' : 'Pause'}
            </button>
          </div>
        )}
      </div>
    );
  }