0

我在使用某些 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”日志行。我查看了系统日志,但找不到任何说明为什么它没有被授予的信息。

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

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

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 回答