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);
您也可以尝试https://github.com/luminos-software/react-native-play-sound。 –