简体   繁体   English

媒体播放器给我空指针异常

[英]mediaplayer gives me null pointer exception

I want my code to play a sound file at MAX volume when a button is pressed. 我希望我的代码在按下按钮时以最大音量播放声音文件。 My code works perfectly fine just playing the sound file, but when I throw in originalVolume 我的代码仅播放声音文件就可以正常工作,但是当我输入originalVolume

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

My program crashes upon the click of the button. 单击该按钮,我的程序崩溃。

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

            }
        });

    }

From code you have shown above, mAudioManager is null all the time. 根据上面显示的代码,mAudioManager始终为null。 So its obvious why you get NPE. 所以很明显为什么要获得NPE。

you forgot this line: 您忘记了这一行:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM