React Native Expo-Video and using “timeUpdate”
For SDK 52
This article is meant as overkill for the Expo-Video documentation which is already good, however, I had trouble implementing the handler for the “timeUpdate” event.
In case you want to skip right to my code I have a GitHub Repository here: https://github.com/costa-rica/native-stuff-10. See the file /screens/PlayVideo/PlayVideoStackoverflow.js.
Step 1: Install expo-video player
npx expo install expo-video
Step 2: Implement the video player
See the code in the documentation or here is an event simpler version
import { useVideoPlayer, VideoView } from "expo-video";
import { StyleSheet, View, Dimensions } from "react-native";
const videoSource =
"https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4";
export default function Player() {
const player = useVideoPlayer(videoSource, (player) => {
player.loop = true;
player.play();
});
return (
<View>
<VideoView style={styles.vwVideo} player={player} />
</View>
);
}
const styles = StyleSheet.create({
vwVideo: {
width: Dimensions.get("window").width,
height: 300,
},
});
Step 3: Add event handler
After you have added <VideoView> to you project and the video is running you’ll need two critical steps.
Step 3.1: add the timeUpdateEventInterval
This can go in your player object called back like this.
const player = useVideoPlayer(videoSource, (player) => {
player.loop = true;
player.play();
player.timeUpdateEventInterval = 1; //< — — critical for event
});
This tells the player how often do you want the handler to trigger.
Step 3.2: add the event
Here is one way. Place this code in the logic section of your component:
useEventListener(player, “timeUpdate”, (payload) => {
console.log(“Player status changed: “, payload.currentTime);
});
All the code
import { useEventListener } from "expo";
import { useVideoPlayer, VideoView } from "expo-video";
import { StyleSheet, View, Dimensions } from "react-native";
const videoSource =
"https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4";
export default function Player() {
const player = useVideoPlayer(videoSource, (player) => {
player.loop = true;
player.play();
player.timeUpdateEventInterval = 1;
});
useEventListener(player, "timeUpdate", (payload) => {
console.log("Player status changed: ", payload.currentTime);
});
return (
<View>
<VideoView style={styles.vwVideo} player={player} />
</View>
);
}
const styles = StyleSheet.create({
vwVideo: {
width: Dimensions.get("window").width,
height: 300,
},
});