How can I stop the current song and play the next song?

I am using React Native and React Native Sound to create an audio player, but I am facing some problems right now. My problem is that I want to stop the current song and play the next song, and I don't know how. Here is my code:

I am using React, React Native and React Native Sound.

export default class PlaySound extends Component {

  constructor(props) {
    super(props);

    this.state = {
      stop: false,
      playing: false
    };

    this.stopTrack = () => {
     if(!this.state.playing){
       return;
     }
      this.setState({ stop: false });
      this.state.playing.stop();
    }
  }

  renderTrackButton(track){
    if(this.state.stop){
      return (
        <Button danger onPress={() => this.stopTrack()}>
          <Text>Stop</Text>
        </Button>
      );
    }else{
      return (
        <Button onPress={() => this.playTrack(track)}>
          <Text>Play</Text>
        </Button>
      );
    }
  }


  playTrack = (track) => {
    const callback =(error, sound) => {
      if(error) throw error;
      this.setState({ stop: true, playing: sound });
      sound.play();
    }
    const sound = new Sound(track.url, error => callback(error, sound));
  }

  render() {
    console.log(this.state);
    return (
      <Container>
        <Header>
          <Text style={{ color:'white', fontWeight:'bold', marginTop:15 }}>Play Sound Demo</Text>
          <Right>
            <Icon name="heart" />
          </Right>
        </Header>
        <Content>
          {tracks.map((track) => (
            <Card key={track.chinese}>
              <CardItem>
                <Body>
                  <Text>{track.pinyin}</Text>
                  <Text>{track.chinese}</Text>
                </Body>
                <Right>
                  {this.renderTrackButton(track)}
                </Right>
              </CardItem>
            </Card>
          ))}
        </Content>
      </Container>
    );
  }
}

AppRegistry.registerComponent('PlaySound', () => PlaySound);

      

+3


source to share





All Articles