Skip to content

Video

Examples#

Example 1#

example_1.py
import random

import flet as ft

import flet_video as ftv


def main(page: ft.Page):
    page.theme_mode = ft.ThemeMode.LIGHT
    page.title = "TheEthicalVideo"
    page.window.always_on_top = True
    page.spacing = 20
    page.horizontal_alignment = ft.CrossAxisAlignment.CENTER

    def handle_pause(e):
        video.pause()
        print("Video.pause()")

    def handle_play_or_pause(e):
        video.play_or_pause()
        print("Video.play_or_pause()")

    def handle_play(e):
        video.play()
        print("Video.play()")

    def handle_stop(e):
        video.stop()
        print("Video.stop()")

    def handle_next(e):
        video.next()
        print("Video.next()")

    def handle_previous(e):
        video.previous()
        print("Video.previous()")

    def handle_volume_change(e):
        video.volume = e.control.value
        page.update()
        print(f"Video.volume = {e.control.value}")

    def handle_playback_rate_change(e):
        video.playback_rate = e.control.value
        page.update()
        print(f"Video.playback_rate = {e.control.value}")

    def handle_seek(e):
        video.seek(10000)
        print("Video.seek(10000)")

    def handle_add_media(e):
        video.playlist_add(random.choice(sample_media))
        print("Video.playlist_add(random.choice(sample_media))")

    def handle_remove_media(e):
        r = random.randint(0, len(video.playlist) - 1)
        video.playlist_remove(r)
        print(f"Popped Item at index: {r} (position {r + 1})")

    def handle_jump(e):
        print("Video.jump_to(0)")
        video.jump_to(0)

    sample_media = [
        ftv.VideoMedia(
            "https://user-images.githubusercontent.com/28951144/229373720-14d69157-1a56-4a78-a2f4-d7a134d7c3e9.mp4"
        ),
        ftv.VideoMedia(
            "https://user-images.githubusercontent.com/28951144/229373718-86ce5e1d-d195-45d5-baa6-ef94041d0b90.mp4"
        ),
        ftv.VideoMedia(
            "https://user-images.githubusercontent.com/28951144/229373716-76da0a4e-225a-44e4-9ee7-3e9006dbc3e3.mp4"
        ),
        ftv.VideoMedia(
            "https://user-images.githubusercontent.com/28951144/229373695-22f88f13-d18f-4288-9bf1-c3e078d83722.mp4"
        ),
        ftv.VideoMedia(
            "https://user-images.githubusercontent.com/28951144/229373709-603a7a89-2105-4e1b-a5a5-a6c3567c9a59.mp4",
            extras={
                "artist": "Thousand Foot Krutch",
                "album": "The End Is Where We Begin",
            },
            http_headers={
                "Foo": "Bar",
                "Accept": "*/*",
            },
        ),
    ]

    page.add(
        video := ftv.Video(
            expand=True,
            playlist=sample_media[0:2],
            playlist_mode=ftv.PlaylistMode.LOOP,
            fill_color=ft.Colors.BLUE_400,
            aspect_ratio=16 / 9,
            volume=100,
            autoplay=False,
            filter_quality=ft.FilterQuality.HIGH,
            muted=False,
            on_load=lambda e: print("Video loaded successfully!"),
            on_enter_fullscreen=lambda e: print("Video entered fullscreen!"),
            on_exit_fullscreen=lambda e: print("Video exited fullscreen!"),
        ),
        ft.Row(
            wrap=True,
            alignment=ft.MainAxisAlignment.CENTER,
            controls=[
                ft.ElevatedButton("Play", on_click=handle_play),
                ft.ElevatedButton("Pause", on_click=handle_pause),
                ft.ElevatedButton("Play Or Pause", on_click=handle_play_or_pause),
                ft.ElevatedButton("Stop", on_click=handle_stop),
                ft.ElevatedButton("Next", on_click=handle_next),
                ft.ElevatedButton("Previous", on_click=handle_previous),
                ft.ElevatedButton("Seek s=10", on_click=handle_seek),
                ft.ElevatedButton("Jump to first Media", on_click=handle_jump),
                ft.ElevatedButton("Add Random Media", on_click=handle_add_media),
                ft.ElevatedButton("Remove Random Media", on_click=handle_remove_media),
            ],
        ),
        ft.Slider(
            min=0,
            value=100,
            max=100,
            label="Volume = {value}%",
            divisions=10,
            width=400,
            on_change=handle_volume_change,
        ),
        ft.Slider(
            min=1,
            value=1,
            max=3,
            label="PlaybackRate = {value}X",
            divisions=6,
            width=400,
            on_change=handle_playback_rate_change,
        ),
    )


ft.app(main)

Video #

Bases: ConstrainedControl

A control that displays a video from a playlist.

RAISES DESCRIPTION
AssertionError

If the volume is not between 0.0 and 100.0 (inclusive).

align #

align: Alignment | None = None

Alignment of the control within its parent.

alignment #

alignment: Alignment = field(default_factory=lambda: CENTER)

Defines the Alignment of the viewport.

animate_align #

animate_align: AnimationValue | None = None

Enables implicit animation of the align property.

More information here.

animate_margin #

animate_margin: AnimationValue | None = None

Enables implicit animation of the margin property.

More information here.

animate_offset #

animate_offset: AnimationValue | None = None

Enables implicit animation of the offset property.

More information here.

animate_opacity #

animate_opacity: AnimationValue | None = None

Enables implicit animation of the opacity property.

More information here.

animate_position #

animate_position: AnimationValue | None = None

Enables implicit animation of the positioning properties (left, right, top and bottom).

More information here.

animate_rotation #

animate_rotation: AnimationValue | None = None

Enables implicit animation of the rotate property.

More information here.

animate_scale #

animate_scale: AnimationValue | None = None

Enables implicit animation of the scale property.

More information here.

animate_size #

animate_size: AnimationValue | None = None

TBD

aspect_ratio #

aspect_ratio: Number | None = None

TBD

autoplay #

autoplay: bool = False

Whether the video should start playing automatically.

badge #

badge: BadgeValue | None = None

A badge to show on top of this control.

bottom #

bottom: Number | None = None

The distance that the child's bottom edge is inset from the bottom of the stack.

Note

Effective only if this control is a descendant of one of the following: Stack control, Page.overlay list.

col #

col: ResponsiveNumber = 12

If a parent of this control is a ResponsiveRow, this property is used to determine how many virtual columns of a screen this control will span.

Can be a number or a dictionary configured to have a different value for specific breakpoints, for example col={"sm": 6}.

This control spans the 12 virtual columns by default.

/// details | Dimensions type: info | Breakpoint | Dimension | |---|---| | xs | <576px | | sm | ≥576px | | md | ≥768px | | lg | ≥992px | | xl | ≥1200px | | xxl | ≥1400px | ///

configuration #

configuration: VideoConfiguration = field(
    default_factory=lambda: VideoConfiguration()
)

Additional configuration for the video player.

data #

data: Any = skip_field()

Arbitrary data of any type.

disabled #

disabled: bool = False

Every control has disabled property which is False by default - control and all its children are enabled.

Note

The value of this property will be propagated down to all children controls recursively.

/// details | Example type: example For example, if you have a form with multiple entry controls you can disable them all together by disabling container:

ft.Column(
    disabled = True,
    controls=[
        ft.TextField(),
        ft.TextField()
    ]
)
///

expand #

expand: bool | int | None = None

Specifies whether/how this control should expand to fill available space in its parent layout.

More information here.

Note

Has effect only if the direct parent of this control is one of the following controls, or their subclasses: Column, Row, View, Page.

expand_loose #

expand_loose: bool = False

Allows the control to expand along the main axis if space is available, but does not require it to fill all available space.

More information here.

Note

If expand_loose is True, it will have effect only if:

  • expand is not None and
  • the direct parent of this control is one of the following controls, or their subclasses: Column, Row, View, Page.

fill_color #

fill_color: ColorValue = BLACK

Defines the color used to fill the video background.

filter_quality #

filter_quality: FilterQuality = LOW

Filter quality of the texture used to render the video output.

Note

Android was reported to show blurry images when using FilterQuality.HIGH. Prefer the usage of FilterQuality.MEDIUM on this platform.

fit #

fit: BoxFit = CONTAIN

The box fit to use for the video.

height #

height: Number | None = None

Imposed Control height in virtual pixels.

key #

key: KeyValue | None = None

left #

left: Number | None = None

The distance that the child's left edge is inset from the left of the stack.

Note

Effective only if this control is a descendant of one of the following: Stack control, Page.overlay list.

margin #

margin: MarginValue | None = None

Sets the margin of the control.

muted #

muted: bool = False

Defines whether the video player should be started in muted state.

offset #

offset: OffsetValue | None = None

Applies a translation transformation before painting the control.

The translation is expressed as an Offset scaled to the control's size. So, Offset(x=0.25, y=0), for example, will result in a horizontal translation of one quarter the width of this control.

/// details | Example type: example The following example displays container at 0, 0 top left corner of a stack as transform applies -1 * 100, -1 * 100 (offset * control's size) horizontal and vertical translations to the control:

import flet as ft

def main(page: ft.Page):
    page.add(
        ft.Stack(
            width=1000,
            height=1000,
            controls=[
                ft.Container(
                    bgcolor="red",
                    width=100,
                    height=100,
                    left=100,
                    top=100,
                    offset=ft.Offset(-1, -1),
                )
            ],
        )
    )

ft.run(main)
///

on_animation_end #

on_animation_end: (
    ControlEventHandler[LayoutControl] | None
) = None

Called when animation completes.

Can be used to chain multiple animations.

The data property of the event handler argument contains the name of the animation.

More information here.

on_complete #

on_complete: ControlEventHandler[Video] | None = None

Fires when a video player completes.

on_enter_fullscreen #

on_enter_fullscreen: ControlEventHandler[Video] | None = (
    None
)

Fires when the video player enters fullscreen.

on_error #

on_error: ControlEventHandler[Video] | None = None

Fires when an error occurs.

Event handler argument's data property contains information about the error.

on_exit_fullscreen #

on_exit_fullscreen: ControlEventHandler[Video] | None = None

Fires when the video player exits fullscreen

on_load #

on_load: ControlEventHandler[Video] | None = None

Fires when the video player is initialized and ready for playback.

on_track_change #

on_track_change: ControlEventHandler[Video] | None = None

Fires when a video track changes.

Event handler argument's data property contains the index of the new track.

opacity #

opacity: Number = 1.0

Defines the transparency of the control.

Value ranges from 0.0 (completely transparent) to 1.0 (completely opaque without any transparency).

page #

page: Page | BasePage | None

The page to which this control belongs to.

parent #

parent: BaseControl | None

The direct ancestor(parent) of this control.

It defaults to None and will only have a value when this control is mounted (added to the page tree).

The Page control (which is the root of the tree) is an exception - it always has parent=None.

pause_upon_entering_background_mode #

pause_upon_entering_background_mode: bool = True

Whether to pause the video when application enters background mode.

pitch #

pitch: Number = 1.0

Defines the relative pitch of the video player.

playback_rate #

playback_rate: Number = 1.0

Defines the playback rate of the video player.

playlist #

playlist: list[VideoMedia] = field(default_factory=list)

A list of VideoMedias representing the video files to be played.

playlist_mode #

playlist_mode: PlaylistMode | None = None

Represents the mode of playback for the playlist.

resume_upon_entering_foreground_mode #

resume_upon_entering_foreground_mode: bool = False

Whether to resume the video when application enters foreground mode. Has effect only if pause_upon_entering_background_mode is also set to True.

right #

right: Number | None = None

The distance that the child's right edge is inset from the right of the stack.

Note

Effective only if this control is a descendant of one of the following: Stack control, Page.overlay list.

rotate #

rotate: RotateValue | None = None

Transforms this control using a rotation around its center.

The value of rotate property could be one of the following types:

  • number - a rotation in clockwise radians. Full circle 360° is math.pi * 2 radians, 90° is pi / 2, 45° is pi / 4, etc.
  • Rotate - allows to specify rotation angle as well as alignment - the location of rotation center.

/// details | Example type: example For example:

ft.Image(
    src="https://picsum.photos/100/100",
    width=100,
    height=100,
    border_radius=5,
    rotate=Rotate(angle=0.25 * pi, alignment=ft.Alignment.CENTER_LEFT)
)
///

rtl #

rtl: bool = False

Whether the text direction of the control should be right-to-left (RTL).

scale #

scale: ScaleValue | None = None

Scales this control along the 2D plane. Default scale factor is 1.0, meaning no-scale.

Setting this property to 0.5, for example, makes this control twice smaller, while 2.0 makes it twice larger.

Different scale multipliers can be specified for x and y axis, by setting Control.scale property to an instance of Scale class. Either scale or scale_x and scale_y could be specified, but not all of them.

/// details | Example type: example

ft.Image(
    src="https://picsum.photos/100/100",
    width=100,
    height=100,
    border_radius=5,
    scale=ft.Scale(scale_x=2, scale_y=0.5)
)
///

show_controls #

show_controls: bool = True

Whether to show the video player controls.

shuffle_playlist #

shuffle_playlist: bool = False

Defines whether the playlist should be shuffled.

subtitle_configuration #

subtitle_configuration: VideoSubtitleConfiguration = field(
    default_factory=lambda: VideoSubtitleConfiguration()
)

Defines the subtitle configuration for the video player.

subtitle_track #

subtitle_track: VideoSubtitleTrack | None = None

Defines the subtitle track for the video player.

title #

title: str = 'flet-video'

Defines the name of the underlying window & process for native backend. This is visible inside the windows' volume mixer.

tooltip #

tooltip: TooltipValue | None = None

The tooltip ot show when this control is hovered over.

top #

top: Number | None = None

The distance that the child's top edge is inset from the top of the stack.

Note

Effective only if this control is a descendant of one of the following: Stack control, Page.overlay list.

visible #

visible: bool = True

Every control has visible property which is True by default - control is rendered on the page. Setting visible to False completely prevents control (and all its children if any) from rendering on a page canvas. Hidden controls cannot be focused or selected with a keyboard or mouse and they do not emit any events.

volume #

volume: Number = 100.0

Defines the volume of the video player.

Note

It's value ranges between 0.0 to 100.0 (inclusive), where 0.0 is muted and 100.0 is the maximum volume. An exception will be raised if the value is outside this range.

wakelock #

wakelock: bool = True

Whether to acquire wake lock while playing the video. When True, device's display will not go to standby/sleep while the video is playing.

width #

width: Number | None = None

Imposed Control width in virtual pixels.

before_event #

before_event(e: ControlEvent)

before_update #

before_update()

build #

build()

Called once during control initialization to define its child controls. self.page is available in this method.

clean #

clean() -> None

did_mount #

did_mount()

get_current_position #

get_current_position() -> Duration
RETURNS DESCRIPTION
Duration

The current position of the currently playing media.

get_duration #

get_duration() -> Duration
RETURNS DESCRIPTION
Duration

The duration of the currently playing media.

init #

init()

is_completed #

is_completed() -> bool
RETURNS DESCRIPTION
bool

True if video player has reached the end of the currently playing media, False otherwise.

is_isolated #

is_isolated()

is_playing #

is_playing() -> bool
RETURNS DESCRIPTION
bool

True if the video player is currently playing, False otherwise.

jump_to #

jump_to(media_index: int)

Jumps to the VideoMedia at the specified media_index in the playlist.

next #

next()

Jumps to the next VideoMedia in the playlist.

pause #

pause()

Pauses the video player.

play #

play()

Starts playing the video.

play_or_pause #

play_or_pause()

Cycles between play and pause states of the video player, i.e., plays if paused and pauses if playing.

playlist_add #

playlist_add(media: VideoMedia)

Appends/Adds the provided media to the playlist.

playlist_remove #

playlist_remove(media_index: int)

Removes the provided media from the playlist.

previous #

previous()

Jumps to the previous VideoMedia in the playlist.

seek #

seek(position: DurationValue)

Seeks the currently playing VideoMedia from the playlist at the specified position.

stop #

stop()

Stops the video player.

update #

update() -> None

will_unmount #

will_unmount()