I'm having an issue with some android code to play a sound notification on certain events.
Here's the code:
int result = audioManager.requestAudioFocus(MainRunningService.afChangeListener,AudioManager.STREAM_NOTIFICATION,AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK);
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
mp = new MediaPlayer();
mp.setDataSource(context, soundToPlay);
mp.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
mp.prepare();
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mediaPlayer) {
try {
Log.d(LOGTAG, "SoundService MUSIC: MUSIC IS NOW COMPLETE");
mp.release();
mp = null;
Log.d(LOGTAG, "SoundService MUSIC: MUSIC IS NOW COMPLETE - RELEASED");
} catch (Exception e) {
e.printStackTrace();
}
}
});
mp.setLooping(false);
mp.start();
}
else{
Log.w(LOGTAG, "SoundService Audiofocus was not granted");
}
What I'm finding is that sometimes it will play, whereas other times it won't play. When it doesn't play it's hitting the "SoundSerice Audiofocus was not granted" log line. I've looked at the system logs, but can't find anything that says why it's not been granted.
Once this has happened, then every request seems to fail.
Does anyone have any pointers to what I might be doing wrong?