2017-08-02 230 views
3

我正在使用React Native和React Native Sound創建一個音頻播放器,但現在我面臨一些問題。我的問題是我想停止當前播放的歌曲並播放下一首歌曲,但我不知道如何操作。這裏是我的代碼:如何停止當前播放的歌曲並播放下一首歌曲?

我正在使用React,React Native和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); 

回答

0

在那裏,你可以找到一個完整的工作示例反應本機模塊播放音頻流,與後臺支持和媒體控制。學習東西的最佳方式是從一個好例子https://github.com/tlenclos/react-native-audio-streaming

+0

您也可以嘗試https://github.com/luminos-software/react-native-play-sound。 –

相關問題