【问题标题】:I wanna create a music list in react. How can I create it?我想在反应中创建一个音乐列表。我怎样才能创建它?
【发布时间】:2019-07-19 10:47:53
【问题描述】:

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

我已经尝试过使用音频。

这是我的渲染函数 -

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>
        );
    }

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

constructor(props) {
        super(props);
        this.state = {
            play: false
        }
    }

    audio = new Audio("http://streaming.tdiradio.com:8000/house.mp3")

    togglePlay = () => {
        this.setState({ play: !this.state.play }, () => {
            this.state.play ? this.audio.play() : this.audio.pause();
        });
    }

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

【问题讨论】:

    标签: reactjs audio audio-player


    【解决方案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>
        );
      }
    

    【讨论】:

      猜你喜欢
      • 2022-12-10
      • 2017-08-11
      • 2017-07-01
      • 1970-01-01
      • 2011-04-27
      • 2017-07-06
      • 2022-10-24
      • 2020-01-17
      • 2018-01-14
      相关资源
      最近更新 更多