Android 如何在另一个活动中单击图像按钮时播放声音?

Android 如何在另一个活动中单击图像按钮时播放声音?,android,audio,onclick,android-mediaplayer,android-imagebutton,Android,Audio,Onclick,Android Mediaplayer,Android Imagebutton,我正在尝试创建一个图像按钮的方法。单击后,背景音乐停止,图像按钮变为另一个图像。当再次按下时,它会像第一次一样返回并重放音乐 我在尝试布尔运算。当它是真的,音乐开始,当它是假的音乐,但它不工作 此外,如何根据主要活动播放或停止其他活动的音乐 public class MainActivity extends AppCompatActivity { MediaPlayer mp; ImageButton SoundButton; ImageButton NoSoundBu

我正在尝试创建一个图像按钮的方法。单击后,背景音乐停止,图像按钮变为另一个图像。当再次按下时,它会像第一次一样返回并重放音乐

我在尝试布尔运算。当它是真的,音乐开始,当它是假的音乐,但它不工作

此外,如何根据主要活动播放或停止其他活动的音乐

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();

当然,还要确保音频文件存在


2)如何传递按钮状态

您可以在如下活动之间使用Bundle传递按钮状态

开始活动2

Intent intent = new Intent(this, Activity2.class);
intent.putExtra(EXTRA_NAME, VALUE);
startActivity(intent);
在活动2中获取该值,如

@Override
protected void onCreate(Bundle savedInstanceState) {
....
boolean value = getIntent().getExtras().getBoolean(EXTRA_VALUE);
}
然后像上面一样,将其传递给活动3


您可以在“活动1”中创建一个静态变量,然后从“活动3”访问该变量。

请提供您目前使用的代码。我们必须知道:您使用什么来播放音乐?你是如何改变你的照片的?您是否设置了onclicklistener等。编辑您的问题并插入代码Dont put MediaPlayer mp=new MediaPlayer();到它现在所在的地方。将其放入onCreate方法中“onCreate”中刚刚知道mp!在“sound”方法中,它是未知的,然后将mediaplayer mp全局放置或将mediaplayer作为参数传递更新了我的代码。。现在试试,顺便说一句,你注意到你从来没有调用过“声音”方法吗?它是通过“onClick”调用的,我尝试了你的代码,当我按下图像按钮时停止了,但是当我再次按下它时,音乐就再也没有播放过@Cédric Portmann考虑放置mp.reset();在mp.stop()方法之后。
@Override
protected void onCreate(Bundle savedInstanceState) {
....
boolean value = getIntent().getExtras().getBoolean(EXTRA_VALUE);
}