我遵循了建议的 Twilio 音频调试但没有得到任何结果,在玩了他们建议的内容之后,我能够创建这个函数,我在使用 Twilio 的活动的 onCreate 中调用它
private fun requestAudioFocus() {
val playbackAttributes = AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_ASSISTANCE_SONIFICATION)
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
.build()
val focusRequest = AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN_TRANSIENT)
.setAudioAttributes(playbackAttributes)
.setAcceptsDelayedFocusGain(true)
.setOnAudioFocusChangeListener { }
.build()
audioManager.requestAudioFocus(focusRequest)
audioManager.isSpeakerphoneOn = !isHeadphonesPlugged(this)
}
并且检查耳机功能是
fun isHeadphonesPlugged(context:Context): Boolean {
val audioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager?
val audioDevices = audioManager!!.getDevices(AudioManager.GET_DEVICES_ALL)
for (deviceInfo in audioDevices) {
if (deviceInfo.type == AudioDeviceInfo.TYPE_WIRED_HEADPHONES
|| deviceInfo.type == AudioDeviceInfo.TYPE_WIRED_HEADSET) {
return true
}
}
return false
}
我在调用 requestFocus() 之前定义了音频管理器
audioManager = this.getSystemService(Context.AUDIO_SERVICE) as AudioManager
希望这可以帮助某人!