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
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. So its obvious why you get NPE.
you forgot this line:
mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);