0

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?

4

1 に答える 1

0

// ボタンのクリック時または任意の場所でメソッド playAssistClip() を呼び出します。

private MediaPlayer mp;
    private void playAssistClip() {
            if (workoutReps.equalsIgnoreCase("6x6x6")) {
                mp = MediaPlayer.create(ProcessWorkout.this,
                        R.raw.six_six_six_formated_ogg);
                mp.setOnCompletionListener(new OnCompletionListener() {

                    //do something after the audi ends
                        mp.reset();
                        mp.release();
                        finish();
                    }

                });
                mp.start();
               //to get the duration of clip
                spentTimeOnWorkout = mp.getDuration();

            }
于 2013-06-27T09:10:15.123 に答える