2014-01-14 58 views
0

我希望我的代碼在按下按鈕時以最大音量播放聲音文件。我的代碼工作完全正常只是在玩聲音文件,但是當我在originalVolumemediaplayer給我空指針異常

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

從上面顯示的代碼可知,mAudioManager始終爲空。所以很明顯你爲什麼會得到NPE。

你忘了這行:

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

沒錯,就是這樣,謝謝。 –