Autoplay video in react material-ui CardMedia component
Asked Answered
D

3

9

I have a Material UI Card component that I'd like to have contain a video (webm) that autoplays. (It's a mute video)

The documentation for the CardMedia component indicates to list any HTML element as the component element type -- so I have listed "video".

I have tried playing with suggestions from here: Video autoplay not working - Trying to find a fix

Specifically, I've tried added component: 'video autoPlay muted to no avail - getting an error that the element cannot be created. I also tried passing an actual tag: <video autoPlay muted>... also failure ('expecting string').

<Card className={classes.root} raised={true}>
        <CardHeader
            title={camera.cameraName}
        />

        <CardActionArea>
            <CardMedia
                component='video'
                className={classes.media}
                image={"path/to/file/video.webm"}
            />
            <CardContent>

                <Typography variant="body2" color="textSecondary" component="p">
                    Some Text
                </Typography>
            </CardContent>
        </CardActionArea>
    </Card>

Any suggestions on how I can get a video to auto play in a MaterialUI CardMedia component?

Alternatively, I'd settle for simply having the controls show up by default - as is, you have to right click and select 'show controls'.

Douglass answered 11/9, 2020 at 7:4 Comment(0)
D
11

React Material UI CardMedia video component not playing led me to the idea that CardMedia appears to simply pass on properties to the 'parent' component (a tag, in this case)

As such, I was able to add an 'autoPlay' property to the CardMedia and it worked.

        <CardMedia
            component='video'
            className={classes.media}
            image={"path/to/file/video.webm"}
            autoPlay
        />

Note that adding 'controls' also added controls to the video.

Douglass answered 11/9, 2020 at 7:7 Comment(1)
can we use youtube link here and is there any other way to manage video in MUINatty
C
4

Also, in case it's helpful to others when using an iframe component, you can set allow="autoPlay" combined with ?autoplay=1&mute in the URL and it will work:

<CardMedia component="iframe" src={video} allow="autoPlay"/>
Cunctation answered 15/10, 2020 at 19:46 Comment(0)
C
0

Another detail to add, browsers policies are designed to prevent unwanted autoplaying of media with sound. Most modern browsers block autoplay by default unless certain conditions are met. Therefore it's often needed to had the muted attribute:

        <CardMedia
            component='video'
            className={classes.media}
            image={"path/to/file/video.webm"}
            autoPlay
            muted
        />
Chemurgy answered 19/8, 2024 at 21:57 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.