播放背景音乐android错误

时间:2015-03-07 08:20:34

标签: java android audio

以下是我知道导致错误的代码:

final MediaPlayer background = MediaPlayer.create(Start.this, R.raw.music);
    background.setLooping(true); // Set looping
    background.setVolume(100,100);
    background.start();

    final ImageButton mute = (ImageButton) findViewById(R.id.mute);
    final boolean[] mute_off = {true};

    mute.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            background.stop();

            if (mute_off[0]) {
                mute.setBackgroundResource(R.drawable.sound_off);
                mute_off[0] = true;
            } else {
                mute.setBackgroundResource(R.drawable.sound_on);
                mute_off[0] = false;
            }
        }
    });

当我启动应用时,它会崩溃,错误是:“很遗憾,应用已停止工作”

由(来自logcat)引起的

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

发生了什么事?

1 个答案:

答案 0 :(得分:0)

您的代码很好,不包括您提供错误的ID或图片不存在于drawable中。这个工作得很好

setContentView(R.layout.activity_main);
        final MediaPlayer background = MediaPlayer.create(this, R.raw.sun);
        background.setLooping(true); // Set looping
        background.setVolume(100,100);
        background.start();

        final ImageButton mute = (ImageButton) findViewById(R.id.edt1);
        final boolean[] mute_off = {true};

        mute.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                background.stop();

                if (mute_off[0]) {
                    Log.v("value is======", "true");
                   // mute.setBackgroundResource(R.drawable.sound_off);
                    mute_off[0] = true;
                } else {
                    Log.v("value is======", "false");
                  //  mute.setBackgroundResource(R.drawable.sound_on);
                    mute_off[0] = false;
                }
            }
        });