我正在尝试创建一个图像按钮的方法。单击它时,背景音乐停止,图像按钮变为另一幅图像。再次按下时,它将像第一次一样返回并重新播放音乐。
我正在尝试 bool 值。当它为真时,音乐开始,当它为假时,音乐开始,但它不起作用!
此外,我如何根据主要 Activity 让另一个 Activity 播放或停止音乐?
public class MainActivity extends AppCompatActivity {
MediaPlayer mp;
ImageButton SoundButton;
ImageButton NoSoundButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SoundButton = new ImageButton(this);
NoSoundButton = new ImageButton(this);
/*---------Image Buttons--------*/
SoundButton=(ImageButton) findViewById(R.id.sound);
SoundButton.setVisibility(View.GONE);
NoSoundButton=(ImageButton) findViewById(R.id.nosound);
NoSoundButton.setVisibility(View.VISIBLE);
/*---------Media Player--------*/
mp = new MediaPlayer();
mp = MediaPlayer.create(this, R.raw.aud);
mp.setLooping(true);
mp.start();
}
public void nosound(View view) {
SoundButton.setVisibility(View.VISIBLE);
NoSoundButton.setVisibility(View.INVISIBLE);
mp.stop();
mp.prepareAsync();
}
public void sound(View view) {
SoundButton.setVisibility(View.INVISIBLE);
NoSoundButton.setVisibility(View.VISIBLE);
mp.start();
}
}
最佳答案
1)您必须更改 MediaPlayer 的初始化位置。
MediaPlayer mp = new MediaPlayer();
public class MainActivity extends AppCompatActivity {
boolean SoundStatus;
MediaPlayer mp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mp = new MediaPlayer();
mp = MediaPlayer.create(this, R.raw.aud);
mp.setLooping(true);
mp.start();
}
public void sound(View view) {
SoundStatus = true;
if (SoundStatus) {
mp.stop();
SoundStatus = false;
}
else {
mp.start();
SoundStatus = true;
}
}}
当然还要确保音频文件存在。
2) 如何传递一个按钮状态
您可以使用 Bundle 在 Activity 之间传递按钮状态,如下所示
开始 Activity 2
Intent intent = new Intent(this, Activity2.class);
intent.putExtra(EXTRA_NAME, VALUE);
startActivity(intent);
在 Activity 2 中获取该值,例如
@Override
protected void onCreate(Bundle savedInstanceState) {
....
boolean value = getIntent().getExtras().getBoolean(EXTRA_VALUE);
}
然后像上面一样做,把它传递给Activity 3。
或者
您可以在 Activity 1 中创建一个静态变量,然后从 Activity 3 访问它。
关于android - 如何在另一个 Activity 中点击 ImageButton 时播放声音?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40694251/