从字面上看,大约在2周前第一次开始编码,因此,如果我对问题的描述可能会引起混淆,我深表歉意,但是我会尽力的。
我创建了一个imageButton,当按下它时,我希望这种情况发生:
我希望它进入无限循环。
启动随机音频->停止音频->启动随机音频...
但是使用我的代码(见图片)https://i.stack.imgur.com/2kO9i.png
它现在所做的是:
我尝试了多种更改Intent或使用开关的方法。但是我无法陷入困境。
答案 0 :(得分:0)
这里不需要循环,您可以做的是将boolean
的值设置为true(如果正在播放音乐),如果设置为false,则停止则简单吗?
答案 1 :(得分:0)
您可以简单地执行以下操作:
// 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;
}
}
});
编辑: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()
}
}
});
最佳
答案 2 :(得分:0)
对于您而言,无需添加任何其他变量,只需将代码更改为。
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;
}
}
});
}
}