如何使用开关按钮播放/停止背景音乐上的声音

时间:2017-01-09 13:30:08

标签: android nullpointerexception background-music

我正在Android上开发游戏,我有一个背景音乐,我想停止使用一个开关,这个开关不是我启动音乐的那个,参数的那个。音乐在主菜单中。

这是我的音乐课程:

public class BackgroundMusic  {

private MediaPlayer player;
public Menu context;

public BackgroundMusic(Menu pContext) {

    context = pContext;

    player = MediaPlayer.create(context.getApplicationContext(), R.raw.opening);
    player.setLooping(true);
    player.setVolume(1.0f, 1.0f);
}


public void start() {
    player.start();
}

public void stop(){
    player.pause();
  }
}

以下是我用于交换机的代码:

buttonmusique = (Switch) findViewById(R.id.switch3);
    buttonmusique.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {


        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            Log.e("bouton",String.valueOf(buttonmusique.isChecked()));
            // If the music is playing
            if (isChecked) {
                media.start();
                buttonmusique.setText("Musique On");  //To change the text near to switch
                Log.d("You are :", "Checked");
            } else {
                media.stop();
                // Resume the music player
                buttonmusique.setText("Musique OFF");   //To change the text near to switch
                Log.d("You are :", " Not Checked");

            }
        }
    });

问题在于,如果我按下开关,它会将我发回主菜单(在某些手机上应用程序崩溃)。

这是logcat:

    E/bouton: false
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: pts3.botanicagofinal, PID: 14271
                  java.lang.NullPointerException: Attempt to invoke virtual method 'void pts3.botanicagofinal.BackgroundMusic.stop()' on a null object reference
                      at pts3.botanicagofinal.Parametres$3.onCheckedChanged(Parametres.java:61)
                      at android.widget.CompoundButton.setChecked(CompoundButton.java:156)
                      at android.widget.Switch.setChecked(Switch.java:1071)
                      at android.widget.Switch.toggle(Switch.java:1066)
                      at android.widget.CompoundButton.performClick(CompoundButton.java:120)
                      at android.view.View$PerformClick.run(View.java:22314)
                      at android.os.Handler.handleCallback(Handler.java:751)
                      at android.os.Handler.dispatchMessage(Handler.java:95)
                      at android.os.Looper.loop(Looper.java:241)
                      at android.app.ActivityThread.main(ActivityThread.java:6223)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Application terminated.

我想知道是否有可能为其工作或我的代码中有错误?

提前感谢您的反馈。

0 个答案:

没有答案