I'm building an app that records and plays back video. I would like to do so without affecting background music playback, i.e. if I begin playing a video, I do not want to pause other apps' audio. However, on Lollipop, Android's VideoView class automatically requests audio focus when the private method VideoView.openVideo()
is called:
AudioManager am = (AudioManager) super.getSystemService(name);
am.requestAudioFocus(null, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
Any suggestions on how to get around this?
You may use MediaPlayer + SurfaceView instead.
I got around this with a stupid solution by copying whole source code of
android.widget.VideoView
of Lollipop and removing line you mentioned.Make your own
VideoView
class. don't useextends VideoView
since you can't overrideopenVideo()
method.I don't recommend this as I thinking it's a temporary solution.
VideoView
Changed a lot between 4.1-5.0 so this can make RuntimeException on Android version other than LollipopEdit
I made approach MediaPlayer + SurfaceView as pinxue told us; It respects aspect ratio within
viewWidth
andviewHeight
.Starting with Android SDK 26 you may want to use
VideoView
andFor older version, there's a workaround described here: https://stackoverflow.com/a/31569930/993439
Basically, copy source code of
VideoView
and uncomment following linesuse audioManager.abandonAudioFocus(null)
If you look at the VideoView code you will notice it calls the method audioManager.requestAudioFocus with null for the OnAudioFocusChangeListener. When you register a listener with the AudioManager it uses this method to make an ID for the listener
which generates the same ID every time you use null. So if you call abandonAudioFocus with null it will remove any listener that was added with null as the parameter for the OnAudioFocusChangeListener
The accepted solution does not guarantee compatibility across all Android versions and is a dirty hack more than a true solution. I've tried all forms of hacks to get this working, yet none have worked to my satisfaction.
I have come up with a much better solution though - switch from a
VideoView
to aTextureView
and load it with aMediaPlayer
. There is no difference from the user's perspective, just no more audio stoppage.Here's my use case for playing an MP4 looping: