I’m developing an Android Auto app and trying to play an MP3 file stored in res/raw through the vehicle’s audio system. However, the sound is played on the mobile device instead. Library-managed sounds play correctly through the car’s speakers.
I used MediaPlayer and AudioManager to manage playback and audio focus (code below). I expected the audio to play through the vehicle’s speakers, similar to other system sounds, but it only plays through the mobile device. I am seeking advice on whether my implementation is incorrect or if additional configurations are necessary for Android Auto.
class HelloWorldScreen(carContext: CarContext) : Screen(carContext) {
private lateinit var mediaPlayer: MediaPlayer
private lateinit var audioManager: AudioManager
private lateinit var audioFocusChangeListener: AudioManager.OnAudioFocusChangeListener
init {
lifecycle.addObserver(object : DefaultLifecycleObserver {
override fun onCreate(owner: LifecycleOwner) {
audioManager = carContext.getSystemService(Context.AUDIO_SERVICE) as AudioManager
setupAudioFocusChangeListener()
setupMediaPlayer()
}
override fun onDestroy(owner: LifecycleOwner) {
super.onDestroy(owner)
mediaPlayer.release()
audioManager.abandonAudioFocus(audioFocusChangeListener)
}
})
}
private fun setupMediaPlayer() {
mediaPlayer = MediaPlayer.create(carContext, R.raw.announce)
mediaPlayer.setOnCompletionListener {
audioManager.abandonAudioFocus(audioFocusChangeListener)
}
}
private fun setupAudioFocusChangeListener() {
audioFocusChangeListener = AudioManager.OnAudioFocusChangeListener { focusChange ->
when (focusChange) {
AudioManager.AUDIOFOCUS_LOSS -> mediaPlayer.pause()
}
}
}
private fun requestAudioFocus(): Boolean {
val result = audioManager.requestAudioFocus(
audioFocusChangeListener,
AudioManager.STREAM_NOTIFICATION,
AudioManager.AUDIOFOCUS_GAIN_TRANSIENT
)
return result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED
}
override fun onGetTemplate(): Template {
val row = Row.Builder().setTitle("Hello AndroidX!").build()
return PaneTemplate.Builder(Pane.Builder().addRow(row).build())
.setHeaderAction(Action.APP_ICON)
.setActionStrip(
ActionStrip.Builder()
.addAction(
Action.Builder()
.setTitle("Play")
.setOnClickListener { buttonAction() }
.build())
.build())
.build()
}
private fun buttonAction() {
if (requestAudioFocus()) {
mediaPlayer.start()
}
}
}
SAMMY is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.