Player Methods
Imperative methods available via the player ref.
Overview
While most interactions are handled through props and callbacks, you can also control the player imperatively using a ref. This is useful for building custom controls, triggering actions from external UI, and advanced integrations.
Current Status
The player currently supports:
- Props: Configure via
src,metadata,objectGroups, etc. - Callbacks: React to events via
onEngineReady,onSceneChange,onPlaybackRestricted - Actions: The engine executes actions defined in rules and plugin event handlers
See the Props Reference for currently available options.
Ref API
Access player methods through a React ref:
Using the Ref
1import { useRef } from 'react';2import { MP4EPlayer, type MP4EPlayerRef } from '@mp4e/react';3import '@mp4e/react/styles.css';45function App() {6 const playerRef = useRef<MP4EPlayerRef>(null);78 const handlePlayPause = () => {9 if (playerRef.current?.isPaused()) {10 playerRef.current.play();11 } else {12 playerRef.current?.pause();13 }14 };1516 const handleSeekTo10Seconds = () => {17 playerRef.current?.seek(10);18 };1920 const handleLogState = () => {21 console.log('t=', playerRef.current?.getCurrentTime());22 console.log('frame=', playerRef.current?.getCurrentFrame());23 };2425 return (26 <div>27 <MP4EPlayer28 ref={playerRef}29 src="/video.mp4"30 onEvent={(event) => { if (event === 'state:ready') console.log('Ready!'); }}31 />3233 <div className="controls">34 <button onClick={handlePlayPause}>Play/Pause</button>35 <button onClick={handleSeekTo10Seconds}>Seek to 10s</button>36 <button onClick={handleLogState}>Log state</button>37 </div>38 </div>39 );40}Playback Methods
Control video playback programmatically.
play()asyncStarts or resumes video playback.
Returns: Promise<void>
pause()Pauses video playback.
Returns: void
seek(time)(time: number)Seeks to the specified time in seconds.
Returns: void
seekToFrame(frame)(frame: number)Seeks to the specified frame number.
Returns: void
seekSilently(timeSeconds)(timeSeconds: number)Seeks without triggering engine seeked rules (prevents loops).
Returns: void
setPlaybackRate(rate)(rate: number)Sets the playback speed. Range: 0.25 to 4.0.
Returns: void
setVolume(volume)(volume: number)Sets the volume level. Range: 0.0 to 1.0.
Returns: void
mute()Mutes audio.
Returns: void
unmute()Unmutes audio.
Returns: void
State Methods
Query current player state.
getCurrentTime()Returns the current playback time in seconds.
Returns: number
getCurrentFrame()Returns the current frame number.
Returns: number
getDuration()Returns the total video duration in seconds.
Returns: number
isPaused()Returns whether the video is paused.
Returns: boolean
isMuted()Returns whether the audio is muted.
Returns: boolean
getVolume()Returns the current volume level (0-1).
Returns: number
getPlaybackRate()Returns the current playback rate.
Returns: number
isFullscreen()Returns whether the player is in fullscreen mode.
Returns: boolean
Metadata & State
Access and reload metadata, and query playback loop boundaries.
reloadMetadata(newMetadata?)(newMetadata?: MP4EMetadata | null)Reload metadata without full destroy/reinit. When the engine is already initialized, this performs a soft reload that preserves DOM (no iframe recreation or visible flash). If newMetadata is omitted, the current metadata prop is re-applied.
Returns: void
getEffectiveMetadata()Returns the full metadata object with all overrides applied (host overrides merged on top of the base metadata). Returns null if metadata has not been loaded yet.
Returns: MP4EMetadata | null
getPlaybackStart()Returns the playback loop start time in seconds. This is the time the video will seek to when looping or when setPlaybackStart has been applied via rules.
Returns: number
getPlaybackEnd()Returns the playback loop end time in seconds. Returns -1 if no end boundary is set (plays to the end of the video).
Returns: number
Variable Methods
Read and modify engine variables. The setVariable method triggers the engine's rules pipeline, so any rules listening for variable changes will fire.
setVariable(variableId, value)(variableId: string, value: any)Sets a variable value at runtime. This goes through the engine, so any rules with variable-change conditions will trigger. Plugins listening via onVariableChange will also be notified.
Returns: void
getVariable(variableId)(variableId: string)Returns the current value of a variable. Returns undefined if the variable doesn't exist.
Returns: any
getVariables()Returns a snapshot of all variables as a plain object. Keys are variable IDs, values are current values.
Returns: Record<string, any>
Action Methods
Execute actions and send events programmatically from host code.
executeAction(action)(action: any)Executes a single action programmatically. Convenience wrapper around executeActions.
Returns: void
executeActions(actions)(actions: any[])Executes an array of actions programmatically. Actions are processed through the engine's action executor, so all engine-side effects (variable changes, rule triggers, playback events) apply as if the actions were triggered by a rule.
Returns: void
notify(event, data?)(event: string, data?: any)Sends an event into the engine. This is the universal event entry point — any rules listening for the specified event will fire. Useful for custom host-originated events that drive rule logic.
Returns: void
Scene Methods
Navigate between scenes and query scene state.
goToScene(sceneId)(sceneId: string)Navigates to the specified scene. The engine resolves the scene's start time and seeks the video accordingly. Any scene exit/enter rules will fire.
Returns: void
getCurrentScene()Returns the ID of the currently active scene, or null if no scene is active.
Returns: string | null
Viewer Preferences
Control privacy and accessibility preferences for the current viewer. These preferences are passed to the engine and affect how plugins behave (e.g., respecting do-not-track, reduced motion, high contrast).
setViewerPreferences(prefs)(prefs: Record<string, any>)Sets privacy and accessibility preferences for the viewer. Supported keys include doNotTrack, doNotShareIdentity, limitStorage (privacy) and reducedMotion, highContrast (accessibility). Preferences are sent to the engine and made available to plugins.
Returns: void
getViewerPreferences()Returns the current viewer preferences object. Returns an empty object if no preferences have been set.
Returns: Record<string, any>
Display ControlComing Soon
Programmatically show and hide object and overlay display popups. These methods are available on the underlying engine but not yet exposed on the player ref.
showObjectDisplay(objectId?, eventType?, bbox?)(objectId?: string, eventType?: string, bbox?: number[])Programmatically show an object's display overlay (e.g., tooltip, product card). The eventType determines which display plugin to use (e.g., 'hovered', 'clicked'). The bbox is an optional bounding box [x, y, w, h] in video coordinates for positioning.
Returns: void
hideObjectDisplay(objectId?)(objectId?: string)Hide an object's display overlay. If objectId is omitted, hides all object displays.
Returns: void
showOverlayDisplay(overlayId?, eventType?, boundObjectId?, bbox?)(overlayId?: string, eventType?: string, boundObjectId?: string | null, bbox?: number[])Show an overlay's display popup. For group-bound overlays, provide the boundObjectId to target a specific instance. The bbox provides positioning context in video coordinates.
Returns: void
hideOverlayDisplay(overlayId?, boundObjectId?, eventType?)(overlayId?: string, boundObjectId?: string | null, eventType?: string)Hide an overlay's display popup. For group-bound overlays, provide the boundObjectId to target a specific instance.
Returns: void
Layout & Positioning
Inspect and modify overlay layout, coordinate transforms, and container elements.
updateOverlayStyle(overlayId, styles)(overlayId: string, styles: { x?: number; y?: number; width?: number; height?: number })Dynamically update an overlay's position and/or size at runtime. Values are in the overlay's coordinate units. Only the provided properties are updated; omitted properties remain unchanged.
Returns: void
getOverlayPositions()Returns all computed overlay positions as a Map. Each entry maps an overlay ID to its rendered position data including screen coordinates, dimensions, and visibility state.
Returns: Map<string, RenderedOverlayPosition>
getVideoDisplayTransform()Returns the current video-to-screen coordinate transform. This describes how video-native pixel coordinates map to screen coordinates, accounting for letterboxing, scaling, and aspect ratio. Returns null if the video element is not yet ready.
Returns: VideoDisplayTransform | null
getOverlayContainerRef()Returns the overlay container DOM element. This is the div that contains all overlay iframes and positioned elements. Useful for advanced integrations that need to inject custom DOM alongside overlays.
Returns: HTMLDivElement | null
Object Methods
Query tracked objects and their data.
getVisibleObjects()Returns objects visible in the current frame, including their bounding boxes, polygons, custom data, and group memberships.
Returns: Array<{ id: string; bbox: number[]; polygon?: number[][]; data?: any; groupIds?: string[] }>
getObject(objectId)(objectId: string)Returns object data from the registry by ID. This includes custom data fields defined in the object's group data schema. Returns null if the object doesn't exist.
Returns: any | null
Utility Methods
Fullscreen, metadata, and cleanup.
enterFullscreen()asyncEnters fullscreen mode.
Returns: Promise<void>
exitFullscreen()asyncExits fullscreen mode.
Returns: Promise<void>
toggleFullscreen()asyncToggles fullscreen mode.
Returns: Promise<void>
getVideoElement()Returns the underlying HTMLVideoElement (advanced use only).
Returns: HTMLVideoElement | null
getCanvasElement()Returns the overlay canvas element (advanced use only).
Returns: HTMLCanvasElement | null
Complete Example
1const playerRef = useRef<MP4EPlayerRef>(null);23// Playback control4await playerRef.current?.play();5playerRef.current?.pause();6playerRef.current?.seek(30);7playerRef.current?.seekToFrame(750);8playerRef.current?.setPlaybackRate(1.5);9playerRef.current?.setVolume(0.8);10playerRef.current?.mute();11playerRef.current?.unmute();12playerRef.current?.seekSilently(12.0);1314// Get state15const time = playerRef.current?.getCurrentTime(); // 30.516const frame = playerRef.current?.getCurrentFrame(); // 76317const duration = playerRef.current?.getDuration(); // 12018const paused = playerRef.current?.isPaused(); // false19const muted = playerRef.current?.isMuted(); // false20const volume = playerRef.current?.getVolume(); // 0.821const rate = playerRef.current?.getPlaybackRate(); // 1.522const fullscreen = playerRef.current?.isFullscreen(); // false2324// Metadata & state25const meta = playerRef.current?.getEffectiveMetadata();26playerRef.current?.reloadMetadata(updatedMetadata);27const loopStart = playerRef.current?.getPlaybackStart();28const loopEnd = playerRef.current?.getPlaybackEnd();2930// Variables31playerRef.current?.setVariable('cartCount', 5);32const score = playerRef.current?.getVariable('score'); // 4233const allVars = playerRef.current?.getVariables(); // { score: 42, ... }3435// Actions36playerRef.current?.executeAction({ type: 'pause' });37playerRef.current?.executeActions([38 { type: 'showOverlay', overlayId: 'promo-banner' },39 { type: 'setVariable', variableId: 'promoShown', value: true },40]);41playerRef.current?.notify('custom:purchase', { productId: 'abc' });4243// Scenes44playerRef.current?.goToScene('chapter-2');45const scene = playerRef.current?.getCurrentScene(); // 'chapter-1'4647// Objects48const visible = playerRef.current?.getVisibleObjects(); // [{ id, bbox, ... }]49const chair = playerRef.current?.getObject('obj_chair_1'); // { label, data, ... }5051// Viewer preferences52playerRef.current?.setViewerPreferences({53 doNotTrack: true,54 reducedMotion: true,55});56const prefs = playerRef.current?.getViewerPreferences();5758// Layout & positioning59const transform = playerRef.current?.getVideoDisplayTransform();60const positions = playerRef.current?.getOverlayPositions();61playerRef.current?.updateOverlayStyle('overlay-1', { x: 100, y: 200 });62const container = playerRef.current?.getOverlayContainerRef();6364// Fullscreen65await playerRef.current?.enterFullscreen();66await playerRef.current?.exitFullscreen();67await playerRef.current?.toggleFullscreen();6869// Elements (advanced)70const videoEl = playerRef.current?.getVideoElement();71const canvasEl = playerRef.current?.getCanvasElement();