mediaplayer给我空指针异常

时间:2014-01-14 21:58:15

标签: java android media-player volume android-audiomanager

我希望我的代码在按下按钮时以MAX音量播放声音文件。我的代码在播放声音文件时工作得很好,但是当我扔进originalVolume

int originalVolume = mAudioManager
                        .getStreamVolume(AudioManager.STREAM_MUSIC);
                mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
                        mAudioManager
                                .getStreamMaxVolume(AudioManager.STREAM_MUSIC),
                        0);

点击按钮后我的程序崩溃了。

public class VolumeUp extends Activity {
    TextView text;
    int counter = 0;
    private AudioManager mAudioManager;
    MediaPlayer mediaPlayer = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        text = (TextView) findViewById(R.id.hello);

        text.setOnClickListener(new OnClickListener() {
            public void onClick(View view) {
                int originalVolume = mAudioManager
                        .getStreamVolume(AudioManager.STREAM_MUSIC);
                mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
                        mAudioManager
                                .getStreamMaxVolume(AudioManager.STREAM_MUSIC),
                        0);

                mediaPlayer = MediaPlayer.create(VolumeUp.this,
                        R.raw.policesiren);
                mediaPlayer.setScreenOnWhilePlaying(true);
                mediaPlayer.setLooping(true);// we set the sound to loop.
                mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
                        originalVolume, 0);
                mediaPlayer.start();

            }
        });

    }

1 个答案:

答案 0 :(得分:1)

从上面显示的代码中,mAudioManager始终为null。所以你明白为什么会得到NPE。

你忘记了这句话:

mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);