此刻我有点奇怪的错误。我使用AudioManager播放循环剪辑,但首先请求音频焦点:
private void startPlayer(Sound sound) {
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
int result = audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
initMediaPlayer(sound);
} else {
Toast.makeText(getApplicationContext(), "Could not play audio at the moment...", Toast.LENGTH_LONG).show();
}
}
在我的stop()方法中,我正在运行:
....
if (player != null) {
if (player.isPlaying()) {
player.stop();
}
player.reset();
player.release();
player = null;
}
....
...在我的开始方法中,我使用以下方式初始化播放器:
...
player = MediaPlayer.create(getApplicationContext(), lookupSoundId(sound));
player.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
player.setLooping(true);
player.start();
...
我已经实现了一个onAudioFocusChange方法,该方法会在其他内容播放音频时停止音频。一切都很完美。
@Override
public void onAudioFocusChange(int focusChange) {
switch (focusChange) {
case AudioManager.AUDIOFOCUS_GAIN:
if (player == null) {
initMediaPlayer(currentSound);
} else {
if (!player.isPlaying()) {
play(); // this method updates the UI and starts the player
}
}
player.setVolume(1.0f, 1.0f);
break;
case AudioManager.AUDIOFOCUS_LOSS:
Log.d("onAudioFocusChange", "AudioManager.AUDIOFOCUS_LOSS");
if ((player != null) && (player.isPlaying())) {
stop(); // this method updates the UI and stops the player
}
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
Log.d("onAudioFocusChange", "AudioManager.AUDIOFOCUS_LOSS_TRANSIENT");
if ((player != null) && (player.isPlaying())) {
player.pause();
}
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
Log.d("onAudioFocusChange", "AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK");
if ((player != null) && (player.isPlaying())) {
player.setVolume(0.2f, 0.2f);
}
break;
}
}
我的问题被描述为一系列步骤,因为它有点奇怪,它在安装了Android L开发者预览版(LPV79)的Nexus 5上运行:
另外,在我的stop()方法结束时,我正在调用audioManager.abandonAudioFocus(...);说我现在不需要关注音频。
令人烦恼的是,当我尝试调试它并放入断点时,音频播放正常。我不确定是什么引起了它。 :/