我想创建一个关闭按钮,该按钮可以停止当前播放的歌曲,并在指定的时间(例如5分钟)后播放它,该怎么办?这是我的代码:
onPressButtonPlay() {
if(song != null) {
song.play((success) => {
if(!success)
ToastAndroid.show('Error when play SoundPlayer :(((', ToastAndroid.SHORT);
});
}
}
onPressButtonDismiss() {
if(song != null) {
song.stop((success) => {
if(!success)
ToastAndroid.show('Alarm dismissed', ToastAndroid.SHORT);
});
}
}
onPressButtonStop() {
if(song != null) {
song.stop((success) => {
if(!success)
ToastAndroid.show('Alarm stopped', ToastAndroid.SHORT);
});
}
}
componentDidMount() {
this.timeoutCheck = setTimeout(() => {
this.setTimePassed();
}, 400);
}
setTimePassed() {
this.setState({timePassed: true});
}
onPressButtonTimer() {
if (!this.state.timePassed){
song.play();
}
}
答案 0 :(得分:1)
我解决了我的问题!步骤如下:
在第一个创建功能上,它们将在指定的时间(在这种情况下为一秒钟)后播放警报/音乐:
var SoundPlayer = require('react-native-sound');
var song = null;
export default class App extends Component<{}> {
PlaySongWithDelay=()=>{
setTimeout(function(){
//Put All Your Code Here, Which You Want To Execute After Some Delay Time.
song.play()
}, 1000);
}
componentWillMount() {
song = new SoundPlayer('daydream.mp3', SoundPlayer.MAIN_BUNDLE, (error) => {
if(error)
ToastAndroid.show('Error when init SoundPlayer :(((', ToastAndroid.SHORT);
});
}
之后,创建按钮。这是从上方播放歌曲并停止播放的按钮的代码:
onPressButtonPlay() {
if(song != null) {
song.play((success) => {
if(!success)
ToastAndroid.show('Error when play SoundPlayer :(((', ToastAndroid.SHORT);
});
}
}
onPressButtonDismiss() {
if(song != null) {
song.stop((success) => {
if(!success)
ToastAndroid.show('Alarm dismissed', ToastAndroid.SHORT);
});
}
}
这是绑定两个动作(在x时间后停止并播放)以创建双重动作按钮的功能。
onPressButtonStopAndDismiss(){
this.onPressButtonDismiss();
this.PlaySongWithDelay();
最后编写代码以渲染按钮:
render() {
return (
<View style={styles.container}>
<TouchableOpacity onPress={this.onPressButtonPlay.bind(this)}>
<Text style={styles.buttonText}>Play</Text>
</TouchableOpacity>
<TouchableOpacity onPress={this.onPressButtonStopAndDismiss.bind(this)}>
<Text style={styles.buttonText}>Dismiss</Text>
</TouchableOpacity>
</View>
);
}
我希望这会有所帮助;)
注意:将声音剪辑文件保存在目录android/app/src/main/res/raw