MediaPlayer声音并不总是播放,没有获得授予音频焦点

时间:2013-06-27 08:46:47

标签: android android-mediaplayer

我遇到一些Android代码问题,可以在某些事件上播放声音通知。

以下是代码:

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");
}

我发现的是,有时它会播放,而有时则不会播放。当它没有播放它击中“SoundSerice Audiofocus未授予”日志行。我查看了系统日志,但找不到任何说明为什么没有被授予的日志。

一旦发生这种情况,那么每个请求似乎都会失败。

有没有人指出我可能做错了什么?

1 个答案:

答案 0 :(得分: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();

            }