How to insert video to Sphinx document#

Although it sounds easy, it’s not straightforward. Sadly, pure Sphinx and the underlying library Docutils do not directly support inserting videos into documents. But we will show you two approaches to insert it anyway.

Intro#

When you want to embed a video (mp4, webp, etc.) into HTML generated by Sphinx, you have various approaches. Technically, we want to insert the HTML 5 <video> tag.

Docutils will use the <video> tag if the image filename ends with common video extensions like .mp4. However, the video is static and cannot be played because Docutils doesn’t insert any attributes like a controls to instruct the browser to show play/pause/volume buttons and an autoplay attribute to begin playback automatically.

With sphinxcontrib-video (extension)#

Hopefully, there is a sphinxcontrib-video extension to Sphinx that adds a video directive to insert a video tag.

  1. Install with pip install sphinxcontrib-video.

  2. Add sphinxcontrib.video to extensions in your conf.py.

  3. If video is local, insert file next to your document source, e.g. in videos/.

  4. Insert video with video directive. Directive argument is a path. Local or remote. By default, it displays video with controls.

    .. video:: videos/video.mp4
    
    ```{video} videos/video.mp4
    ```
    
  5. It supports many <video> tag attributes via directive options like autoplay.

    .. video:: videos/video.mp4
       :autoplay:
    
    ```{video} videos/video.mp4
    :autoplay:
    ```
    

Enjoy:

With raw directive (no extensions)#

Use the raw directive, when you don’t want or can’t use the sphixcontrib-video extension. The raw directive is for writing an arbitrary string to the output format.

  1. Create a _static/ folder next to conf.py and configure html_static_path accordingly in conf.py. This will copy the content of _static/ to _static/ in output.

  2. Insert <video> tag.

    .. raw:: html
    
       <video src="../_static/video.mp4" controls autoplay></video>  
    
    ```{raw} html
    <video src="../_static/video.mp4" controls autoplay></video>
    ```
    

The main issue with writing HTML directly with the raw directive is with paths. The path in <video src> must be the output path, not the source path. Have a look at where is an output HTML file placed and use the relative path to the video.

Comments

comments powered by Disqus