In my app I am using a ViewPager (@react-native-community/viewpager) to display several pages. Some of these pages contain videos that I am displaying using react-native-video. If I start a video on one page and then scroll to the next page the video keeps playing in the background. The user can hear the audio of the video although the audio is not visible.
I would like to pause the video when the user scrolls to the next page, how do I accomplish that?
You can store the current page value in state and set some indexes to your pages, like in example below. After that just check if your page is current page:
<ViewPager
initialPage={0}
onPageScroll={({ nativeEvent }) => {
this.setState({
activePage: nativeEvent.position
})
}
}>
<View key="1">
<Video source={{ uri: '' }}
paused={this.state.activePage !== 0} />
</View>
<View key="2">
<Video source={{ uri: '' }}
paused={this.state.activePage !== 1} />
</View>
</ViewPager>
EDIT:
If you do not need the video to auto-start, you can add isPlaying property in state, and set it to true when you need.
<ViewPager
initialPage={0}
onPageScroll={({ nativeEvent }) => {
this.setState({
activePage: nativeEvent.position,
isPlaying: false
})
}
}>
<View key="1">
<Video source={{ uri: '' }}
paused={!this.state.isPlaying || this.state.activePage !== 0} />
</View>
<View key="2">
<Video source={{ uri: '' }}
paused={!this.state.isPlaying || this.state.activePage !== 1} />
</View>
</ViewPager>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With