I have added a webview plugin (official flutter plugin) for viewing webpages. One of the webpage has a youtube video playing and when I press the home button and the app goes into background. But the problem is that the sound keeps on playing. There are other sections in the application that contain some component playing sound or video.
So I want to know what can be done to pause the webview altogether once I move the app to background.
I am currently using this webview plugin: webview_flutter: ^0.3.9+1
There is no option in the plugin to pause the webview itself.
Got the same issue on Android side with webview_flutter: ^0.3.18+1
.
I found a solution to pause the video by requesting audio focus again in the onPause
callback of host Activity
.
val audioManager = activity.getSystemService(Context.AUDIO_SERVICE) as AudioManager
if (audioManager.isMusicActive) {
if (Utils.hasOreoSDK26()) {
val audioAttributes = AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_MEDIA)
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.build()
val audioFocusRequest = AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN_TRANSIENT)
.setAudioAttributes(audioAttributes)
.setAcceptsDelayedFocusGain(true)
.setWillPauseWhenDucked(true)
.setOnAudioFocusChangeListener(
{ focusChange -> Timber.i(">>> Focus change to : %d", focusChange) },
Handler())
.build()
audioManager.requestAudioFocus(audioFocusRequest)
} else {
audioManager.requestAudioFocus({ }, AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN_TRANSIENT)
}
}
Also check this issue.