AudioManager.requestAudioFocus on Lollipop and higher



我目前正在为一个培训应用程序实现一个音频助手,该应用程序可以在您的培训课程中运行一些励志演讲。所以基本上如果一个演讲正在运行,我想躲避我的 Spotify 音频,以便清楚地听到演讲。对于奇巧和奥利奥(及更高(,我已经完成了这项工作(请参阅代码(。但是对于棒棒糖,我找不到正确的实现。在developer.android.com他们写道:

对于以 Android 5.0(API 级别 21(及更高版本为目标平台的应用,音频应用应使用音频属性来描述您的应用正在播放的音频类型。例如,播放语音的应用应指定CONTENT_TYPE_SPEECH。源

但是我从哪里开始,我需要什么才能达到与奇巧和奥利奥相同的结果?(AudioFocusRequest.Builder(( 尚未可用于 API 21 至 API 26。

这是我的代码片段:

/** Apps running Android 8.0 (API level 26) or greater should use the requestAudioFocus() method,
* which takes an AudioFocusRequest parameter. The AudioFocusRequest contains information about
* the audio context and capabilities of your app. The system uses this information to manage
* the gain and loss of audio focus automatically.
*/
@RequiresApi(Build.VERSION_CODES.O)
private fun loadAndPlayAudioForOreoAndHigher() {
val audioAttributes = AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
.build()
val audioFocusRequest = AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK).run {
setAudioAttributes(audioAttributes)
setAcceptsDelayedFocusGain(true)
setOnAudioFocusChangeListener(MediaHelper)
build()
}
val focusRequest = audioManager.requestAudioFocus(audioFocusRequest)
if(focusRequest == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
mediaPlayer.setOnCompletionListener { audioManager.abandonAudioFocusRequest(audioFocusRequest) }
mediaPlayer.start()
}
}
/**
* For apps that target Android 5.0 (API level 21) and later, audio apps should use
* AudioAttributes to describe the type of audio your app is playing. For example,
* apps that play speech should specify CONTENT_TYPE_SPEECH.
*/
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
private fun loadAndPlayAudioForLollipopAndHigher() {
// TODO implement audioFocusRequest() and abandonAudioFocusRequest()
}
/**
* Beginning with Android 2.2 (API level 8), apps manage audio focus by calling
* requestAudioFocus() and abandonAudioFocus(). Apps must also register an
* AudioManager.OnAudioFocusChangeListener with both calls in order to receive callbacks
* and manage their own audio level.
*/
@Suppress("DEPRECATION")
@RequiresApi(Build.VERSION_CODES.KITKAT)
private fun loadAndPlayAudioForKitkatAndHigher() {
val focusRequestResult = audioManager.requestAudioFocus(this, AudioManager.STREAM_NOTIFICATION, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK)
if(focusRequestResult == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
mediaPlayer.setOnCompletionListener { audioManager.abandonAudioFocus(this) }
mediaPlayer.start()
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
videoView.setAudioFocusRequest(AudioManager.AUDIOFOCUS_NONE);
} else {
AudioManager audioManager = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
audioManager.requestAudioFocus(null, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK);
}

相关内容

  • 没有找到相关文章

最新更新