[英]making an Image-button start, stop and restart
Literally started coding for the first time just about 2 weeks ago, so I apologize if my description of the problem might be confusing, but I will try.大约 2 周前第一次开始编码,所以如果我对问题的描述可能令人困惑,我深表歉意,但我会尝试。
I've created an imageButton and when press it I want this to happen:我创建了一个 imageButton,当按下它时,我希望发生这种情况:
I want this to go in a infinite loop.我希望这进入无限循环。
Start random audio -> Stop audio - > Start random audio...开始随机音频 -> 停止音频 -> 开始随机音频...
But with my code (see image) https://i.stack.imgur.com/2kO9i.png但是用我的代码(见图片) https://i.stack.imgur.com/2kO9i.png
what it does right now is:它现在所做的是:
I've tried numerous ways to change the Intent or using a switch instead.我尝试了多种方法来更改 Intent 或使用开关。 But I can't get it to go into a loop.
但我无法让它进入循环。
您不需要在这里循环,您可以做的是将一个boolean
设置为boolean
值,如果正在播放音乐,则为true;如果停止则为false,这是对的吗?
You can simply do this : 您可以简单地做到这一点:
// Delcare a boolean as an attribute to be accessible inside the listener
private boolean isPlaying = false;
// Inside onCreate(), set a listener on your Button myButton
Mediaplayer mp = MediaPlayer.create(this, R.raw.yourfile);
myButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (!isPlaying) {
// Not playing music
// START RANDOM MUSIC with mp.start()
mp.start()
isPlaying = true;
}
else {
// Playing music
// STOP CURRENT PLAYED MUSIC with mp.stop()
mp.stop()
isPlaying = false;
}
}
});
EDIT : MediaPlayer class has a method for this ! 编辑 :MediaPlayer类对此具有方法!
// Inside onCreate(), set a listener on your Button myButton
Mediaplayer mp = MediaPlayer.create(this, R.raw.yourfile);
myButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (!mp.isPlaying()) {
// Not playing music
// START RANDOM MUSIC with mp.start()
mp.start()
}
else {
// Playing music
// STOP CURRENT PLAYED MUSIC with mp.stop()
mp.stop()
}
}
});
Best 最好
In your case, no need to add any extra variable, change your code to. 在您的情况下,无需添加任何额外的变量,只需将代码更改为即可。
public class MainActivity extends Activity {
private final int[] SOUNDS = {R.raw.blizzardlowquaility, R.raw.onebite_dansgaming, R.raw.nagur_dansgaming};
private final int LOW = 0;
private final int HIGH = 3;
private MediaPlayer mMediaPlayer;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageButton Testy = findViewById(R.id.imageButton);
Testy.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mMediaPlayer == null) {
int random = (new Random()).nextInt(HIGH - LOW) + LOW;
mMediaPlayer = MediaPlayer.create(getApplicationContext(), SOUNDS[random]);
mMediaPlayer.start();
} else {
mMediaPlayer.stop();
mMediaPlayer.release();
mMediaPlayer = null;
}
}
});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.