How to embed the video player

This section walks you through the steps of embedding self-hosted and cloud-hosted video players, setting them to play a video from your Media Library, and for a self-hosted player, applying commonly used video player methods and properties.

Embed a basic video player

Tip
You can use the Cloudinary CLI to generate the basic code for embedding a video player:

Copy to clipboard
cld make video_player

You can use the self-hosted player by including the Cloudinary Video Player JavaScript library, giving you full control of all your video player instances. Alternatively, you can embed a cloud-hosted player using an iframe. You can easily generate the code for a customized player using the Cloudinary Video Player Studio, or build this out yourself.

Self-hosted player

Embedding a self-hosted player using the Cloudinary Video Player JavaScript-based library requires more setup and configuration than using the cloud-hosted player. It also requires that the library be included in your website or application. Using the video player library gives you more control over the player and playback. We recommend using this method of embedding if you have multiple player instances, need to programmatically control playback and events, or have advanced customization requirements.

1. Include the relevant CSS and JS files for the video player and JavaScript SDK

The video player package is available in standard and light package variations, each available in either minified or non-minified formats. It also requires the JavaScript cloudinary-core library. You may also need to include additional files depending on the video player features you plan to use.

For example, the following includes the standard, minified package from unpkg.com:

Copy to clipboard
<link href="https://unpkg.com/cloudinary-video-player@1.5.9/dist/cld-video-player.min.css" rel="stylesheet">
<script src="https://unpkg.com/cloudinary-core@latest/cloudinary-core-shrinkwrap.min.js" type="text/javascript"></script>
<script src="https://unpkg.com/cloudinary-video-player@1.5.9/dist/cld-video-player.min.js" 
    type="text/javascript"></script>

For full details on all options, see Installation and setup

Note
When using both the Upload Widget and Video Player on the same page, the video player scripts must be loaded first to prevent any conflicts.

2. Embed the video player by adding a video tag element with the video player class

Create a video tag with at least the cld-video-player class and an id value. You can also include standard HTML5 video player attributes.

Copy to clipboard
<video
  id="demo-player"
  controls
  autoplay
  class="cld-video-player">
</video>

3. Instantiate a Cloudinary instance with your cloudinary configuration

To use the Cloudinary Video Player library you have to configure at least your cloud_name. You can additionally define a number of optional configuration parameters. For example, if you're an Advanced plan user with a private CDN and a custom CNAME, you can set private_cdn to true and configure the cname parameter to match your setup. This will ensure the video player delivers your videos using the correct URLs.

You set configuration parameters while instantiating a new Cloudinary class, for example:

Copy to clipboard
var cld = cloudinary.Cloudinary.new({ cloud_name: "my-cloud", secure: true});

Or for a private CDN and custom distribution:

Copy to clipboard
var cld = cloudinary.Cloudinary.new({ cloud_name: "my-cloud", secure: true, private_cdn: true, secure_distribution: 'example.distribution.com'});

4. Instantiate the Cloudinary video player

Instantiate the video player by using the videoPlayer method and either passing the ID of the video tag ID you defined in step 1, or passing the video element itself. You can optionally add in constructor parameters to set global configurations.

Copy to clipboard
var demoplayer = cld.videoPlayer('demo-player', {<...constructor params here...>} )

Or

Copy to clipboard
var vidElem = document.querySelector("video#demo-player")
var vplayer = cld.videoPlayer(vidElem, {<...constructor params here...>})

If you plan to include multiple players on your page with the same configuration, you can use the videoPlayers method. For example, you can specify different video public IDs for each <video> tag. In this case, there is no need to define id attributes for the <video> tags as you can target the cld-video-player class. As with instantiating a single player, you can optionally add in constructor parameters.

Copy to clipboard
var players = cld.videoPlayers('.cld-video-player', 
 {<...constructor params here...>}
)

5. Specify the video to play and optional player configurations

You can specify the video to play, the transformations to apply, as well as a number of additional configurations either as attributes of the <video> tag or as constructor parameters of the videoPlayer method. These configurations and transformations apply to the video player itself, and thus will apply to all video sources played inside it.

You can additionally specify some options like the video public ID or video URL, video transformations, and the poster source per video source, using videoPlayer.source (or data-cld-source attribute in the <video> tag), and then set different values for these options for each video source you play.

For optimal delivery, you can also define the source types you want the player to use. This can include a combination of advanced formats and codecs as well as adaptive bitrate streaming formats. The player will attempt to play the source type listed first and fallback to the subsequent formats. This helps provide the most optimal video delivery depending on the browser and device.

For the <video> tag, all special Cloudinary video player configurations have a data-cld- prefix. Standard HTML5 video attributes are specified as usual.

Caution
When setting the video player source and any transformations or source types, you will be adjusting the final delivery URLs that the video player will use. As a result, new derived versions of the videos will need to be generated. For videos that exceed the file-size limitations for transforming videos on-the-fly (40 MB for free plans, 100 MB for paid plans), you will need to eagerly generate these derived versions on upload or use the explicit method of the Upload API.

Example 1: Specifying the public ID in the <video> tag:

Copy to clipboard
<video
  id="example-player"
  controls
  muted
  class="cld-video-player cld-video-player-skin-dark"
  data-cld-public-id="myvideo">
</video>


var cld = cloudinary.Cloudinary.new({ cloud_name: 'mycloud' });
var player = cld.videoPlayer('example-player');

Example 2: Specifying the public ID in the videoPlayer method:

Copy to clipboard
<video
  id="example-player"
  controls
  muted
  class="cld-video-player cld-video-player-skin-dark">
</video>

var player = cld.videoPlayer('example-player');
player.source('myvideo');

Example 3: Specifying the video as a URL in the videoPlayer method:

Copy to clipboard
<video
  id="example-player"
  controls
  muted
  class="cld-video-player cld-video-player-skin-dark">
</video>

var player = cld.videoPlayer('example-player');
player.source('http://res.cloudinary.com/demo/video/upload/myvideo.mp4');

Example 4: Specifying multiple source types:

Copy to clipboard
<video
  id="example-player"
  controls
  muted
  class="cld-video-player cld-video-player-skin-dark">
</video>

var player = cld.videoPlayer('example-player', {
  sourceTypes: ['hls','dash','webm/vp9','mp4/h265','mp4']
});
player.source('myvideo');

For details on other configurations you can set, see Configuration options and the Video Player API Reference.

Recommendations for optimal performance

When embedding the self-hosted player, you can embed and configure it in a number of different ways. Some of these provide better performance than others. Here are some recommendations on how to embed the player for the most optimal performance.

  • Use the light package if you aren't using adaptive bitrate streaming, video ads or shoppable video functionality.
  • Ensure your page loads the video player libraries and HTML in the following, most optimal, order:
    1. Video player stylesheet
    2. HTML for the video element
    3. Cloudinary Core and Video Player JavaScript libraries.
    4. JavaScript to configure your video player.
  • Use the cld-fluid class for responsive player sizing. This should be used over any JS configuration method to prevent unwanted player resizing.

Below is a very simple example demonstrating how you should organize your code for the video player using the recommendations above:

Copy to clipboard
<!DOCTYPE html>
<html lang="en">
  <head>
    <link
      rel="stylesheet"
      href="https://unpkg.com/cloudinary-video-player/dist/cld-video-player.light.min.css"
    />
    <title>Video Player Demo</title>
  </head>

  <body>
    <video
      id="player"
      class="cld-video-player cld-fluid"
      controls
      playsinline
    ></video>

    <script src="https://unpkg.com/cloudinary-core/cloudinary-core-shrinkwrap.js"></script>
    <script src="https://unpkg.com/cloudinary-video-player/dist/cld-video-player.light.min.js"></script>

    <script>
      var cld = cloudinary.Cloudinary.new({cloud_name: "demo"});
      var player = cld.videoPlayer("player");
      player.source("dog");
    </script>
  </body>
</html>

Cloud-hosted player

The cloud-hosted player uses an iframe to add an instance of the player to your page. The player itself is hosted by Cloudinary and can be easily configured and customized. You can design and configure your player using the Cloudinary Video Player Studio, and then copy and paste the iframe code it generates for you. Alternatively, you can configure the iframe code manually, as outlined below. We recommend using this method if you don't want to host the video player yourself and want to add individual pre-configured video players to your website or application.

This is a simple example of how video player iframe code might look:

Copy to clipboard
<iframe
  src="https://player.cloudinary.com/embed/?cloud_name=demo&public_id=elephants&fluid=true&controls=true&source_types%5B0%5D=mp4"
  width="640"
  allow="autoplay; fullscreen; encrypted-media; picture-in-picture"
  allowfullscreen
  frameborder="0"
></iframe>

Here's how to code your own cloud-hosted player:

1. Add an iframe to your page or application

Add an <iframe> element to your webpage or application in the location you want the video player to appear. For example:

Copy to clipboard
<html>
  <body>
    <!-- Your web page code -->
    <iframe></iframe>
    <!-- Some more of your web page code -->
  </body>
</html>

2. Set the "src" attribute to your Cloudinary Video Player configuration

Set the src attribute of the iframe to add the video player instance to the iframe. The iframe uses the URL of the Cloudinary Video Player embedder service along with your URL encoded parameters.

The URL structure for the service is - https://player.cloudinary.com/embed/?<parameters>

Note
All parameters in the Video Player API reference are listed in camelCase. When used with the embedder, they must be converted to snake_case. For example showLogo becomes show_logo.

Required parameters

Param Type Description
cloud_name String The cloud name for your Cloudinary account.
public_id String The Cloudinary unique identifier for the video.

Optional parameters

Param Type Description
cloudinary Object The account-specific configuration parameters to apply.
player Object The configuration for the player itself, including the player visuals and behavior.
source Object The configuration to apply to the video source.
vpv String The version of the Cloudinary video player to use.

The simplest way to construct your URL is to build your parameters as a single string and append it to the embed URL, for example:

Copy to clipboard
const params = "cloud_name=demo&public_id=elephants&vpv=1.4.0";
const url = "https://player.cloudinary.com/embed/?"+ params;

This will give you the following URL to set as the src of your iframe:

https://player.cloudinary.com/embed/?cloud_name=demo&public_id=elephants&vpv=1.4.0

Tip
If you're using a variety of parameters and configuration, we recommend building your parameter string as an object and then converting to a URI encoded string. You can use a query-string parsing and stringifying library such as qs to help with this.

Here's an example of building the configuration as an object before stringifying it and appending to the embed URL:

Copy to clipboard
const config = { cloud_name: "demo", public_id: "elephants", cloudinary: { cname: "myCname" }, player: { loop: true }, source: { source_types: ['mp4/h265', 'mp4']} };
const params = qs.stringify(config);
const url = "https://player.cloudinary.com/embed/?"+ params;

This will give you the following URL to set as the src of your iframe:

https://player.cloudinary.com/embed/?cloud_name=demo&public_id=elephants&cloudinary%5Bcname%5D=myCname&player%5Bloop%5D=true&source%5Bsource_types%5D%5B0%5D=mp4%2Fh265&source%5Bsource_types%5D%5B1%5D=mp4

The full HTML code for the iframe using the above URL will be:

Copy to clipboard
<iframe 
  src='https://player.cloudinary.com/embed/?cloud_name=demo&public_id=elephants&cloudinary%5Bcname%5D=myCname&player%5Bloop%5D=true&source%5Bsource_types%5D%5B0%5D=mp4%2Fh265&source%5Bsource_types%5D%5B1%5D=mp4'
></iframe>

3. Set additional iframe attributes

In addition to configuring your embed URL, you need to add some attributes to the <iframe> element to allow the video player to behave as expected. You can add any HTML attribute that an iframe element supports. Below are the attributes we recommend setting:

  • Set frameborder="0" to ensure there's no border around your iframe. Alternatively, you could configure this using CSS by setting border: 0; for your iframe.
  • Set the width and height attributes to control the size of the video player.
  • Set the allow attribute to allow the relevant video player functionality, for example if you want to allow the video to be played in fullscreen or play automatically.

For example, to set your iframe to a width of 500 pixels, remove the border and allow autoplay and fullscreen:

Copy to clipboard
<iframe
  src="your-embed-url"
  width="500px"
  allow="autoplay; fullscreen"
  frameborder="0">
</iframe>

Common video player methods and properties

Once you have embedded a video player in your page or app, you can take advantage of the various video player methods and properties to retrieve the current status of elements and perform a wide variety of actions on the player (self-hosted only). For example, you can retrieve or change the video source that is playing, jump to a specific place in the video, activate video control operations like play, pause, stop, play next or previous, mute/unmute, adjust volume, maximize, and more.

Here are a few simple examples:

  • Set the player volume:

    Copy to clipboard
    vplayer.volume(0.75)
  • Mute the player:

    Copy to clipboard
     vplayer.mute()
  • Jump to the middle of a video:

    Copy to clipboard
    vlength=vplayer.duration()
    middle=vlength/2
    vplayer.currentTime(middle)

All video player methods and properties

For details on all available operations, see the video player methods and playlist operations in the Video Player API Reference.

To view the code for a video player with a set of custom control buttons based on the video player methods, see api.html in the sample CodePen.

Eagerly generating video player URLs

When embedding the video player in your web or mobile application, you can use of a number of configuration parameters to control how your videos look and how they are delivered to your end users. The Cloudinary Video Player itself will also apply some defaults for the delivery formats to ensure optimized performance and wide browser support. As a result, the URLs that are used for delivery will often include some transformations. If you're working with larger videos that exceed the file-size limitations for transforming videos on-the-fly (40 MB for free plans, 100 MB for paid plans), you will need to ensure that you eagerly generate the right URLs to match your configuration.

For example, the default sourceTypes for the video player are ['webm/vp9','mp4/h265','mp4']. This means that the video player will try and deliver a webm version using the vp9 codec before falling back to the others if it is unable to deliver that version. In this scenario, if your original file is an mp4 and the file size exceeds the on-the-fly limit, the webm version will not be generated and the player will need to fallback to a less optimal version. To resolve this, you can ensure that when you upload your videos, you eagerly generate the URLs you require. The same principle applies if you use any transformations on your videos.

Full example

Here's an example of a video player configuration that includes three source types and two transformations to apply to all videos. This is followed by the code required to eagerly generate the matching derived versions of each video.

Simple video player html:

Copy to clipboard
<video
  id="demo-player"
  controls
  autoplay
  class="cld-video-player">
</video>

Video player JavaScript configuration:

Copy to clipboard
var cld = cloudinary.Cloudinary.new({ cloud_name: "demo", secure: true});
var demoplayer = cld.videoPlayer('demo-player', {
  sourceTypes: ['webm/vp9','mp4/h265','mp4'],
  transformation: {
    effect: "vignette",
    border: "5px_solid_black"
  }
});
demoplayer.source("my-video");

The configuration above will generate three delivery URLs, one for each of the defined source types and all three including the transformations we have defined:

  • https://res.cloudinary.com/demo/video/upload/bo_5px_solid_black,e_vignette/vc_vp9/my-video.webm
  • https://res.cloudinary.com/demo/video/upload/bo_5px_solid_black,e_vignette/vc_h265/my-video.mp4
  • https://res.cloudinary.com/demo/video/upload/bo_5px_solid_black,e_vignette/my-video.mp4

Note
The transformations defined in your video player configuration are alphabetized in the delivery URLs. Transforming eagerly using our SDKs, as shown below, will also alphabetize the transformations to ensure they match. Any chained transformations will be created in the order they are chained, so you should ensure you define these in the same order for both.

To ensure that the above URLs are generated and ready for delivery, you can create these eagerly on upload. Here's how to upload your videos with the relevant transformations:

Ruby:
Copy to clipboard
Cloudinary::Uploader.upload(my-video, 
  :resource_type => :video,
  :eager_async => true,
  :eager_notification_url => "https://mysite.example.com/eager_endpoint",
  :eager => [
    { 
      :format => "webm",
      :transformation => [
        { :effect => "vignette", :border=>"5px_solid_black" },
        { :video_codec => "vp9" }
      ]
    },
    { 
      :format => "mp4",
      :transformation => [
        { :effect => "vignette", :border=>"5px_solid_black" },
        { :video_codec => "h265" }
      ]
    },
    { 
      :format => "mp4",
      :transformation => { :effect => "vignette", :border=>"5px_solid_black" }
    }
  ]
)
PHP (cloudinary_php v2.x):
Copy to clipboard
$cloudinary->uploadApi()->upload(my-video, [
  'resource_type' => 'video',
  'eager' => [
    [
      ['format' => 'webm']
      ['effect' => 'vignette', 'border' => '5px_solid_black'],
      ['video_codec' => 'vp9']
    ],
    [
      ['format' => 'mp4']
      ['effect' => 'vignette', 'border' => '5px_solid_black'],
      ['video_codec' => 'h265']
    ],  
    [
      ['format' => 'mp4']
      ['effect' => 'vignette', 'border' => '5px_solid_black'],
    ]
  ],
  'eager_async' => true, 
  'eager_notification_url' => 'https://mysite.example.com/eager_endpoint']);
PHP (cloudinary_php v1.x (legacy)):
Copy to clipboard
\Cloudinary\Uploader::upload(my-video, [
  'resource_type' => 'video',
  'eager' => [
    [
      ['format' => 'webm']
      ['effect' => 'vignette', 'border' => '5px_solid_black'],
      ['video_codec' => 'vp9']
    ],
    [
      ['format' => 'mp4']
      ['effect' => 'vignette', 'border' => '5px_solid_black'],
      ['video_codec' => 'h265']
    ],  
    [
      ['format' => 'mp4']
      ['effect' => 'vignette', 'border' => '5px_solid_black'],
    ]
  ],
  'eager_async' => true, 
  'eager_notification_url' => 'https://mysite.example.com/eager_endpoint']);
Python:
Copy to clipboard
cloudinary.uploader.upload(my-video, 
  resource_type = "video",
  eager = [
    {
      "format": "webm",
      "transformation": [
        {"effect": "vignette", "border":"5px_solid_black"},
        {"video_codec": "vp9"}
      ]
    },
    {
      "format": "mp4",
      "transformation": [
        {"effect": "vignette", "border":"5px_solid_black"},
        {"video_codec": "h265"}
      ]
    },
    {
      "format": "mp4",
      "transformation": {"effect":"vignette", "border":"5px_solid_black"}
    },
  ],
  eager_async = True,
  eager_notification_url = "https://mysite.example.com/eager_endpoint")
Node.js:
Copy to clipboard
cloudinary.v2.uploader.upload(my-video, 
  { resource_type: "video",
    eager_async: true,
    eager_notification_url: "https://mysite.example.com/eager_endpoint", 
    eager: [
            { 
              format: "webm", 
              transformation: [
                {"effect": "vignette", "border":"5px_solid_black"},
                {"video_codec": "vp9"}
              ]
            },
            { 
              format: "mp4", 
              transformation: [
                {"effect": "vignette", "border":"5px_solid_black"},
                {"video_codec": "h265"}
              ]
            },
            { 
              format: "mp4", 
              transformation: {"effect": "vignette", "border":"5px_solid_black"}
            },
          ]
  },
  function(error, result) { console.log(result, error); });
Java:
Copy to clipboard
cloudinary.uploader().upload(my-video, 
  ObjectUtils.asMap(
  "resource_type", "video",
  "eager", Arrays.asList(
    new EagerTransformation()
      .format("webm").chain()
      .effect("vignette").border("5px_solid_black").chain()
      .videoCodec("vp9"),
    new EagerTransformation()
      .format("mp4").chain()
      .effect("vignette").border("5px_solid_black").chain()
      .videoCodec("h265"),
    new EagerTransformation()
      .format("mp4").chain()
      .effect("vignette").border("5px_solid_black")
  ),        
  "eager_async", true,
  "eager_notification_url", "https://mysite.example.com/eager_endpoint"
  )
)
.NET:
Copy to clipboard
var uploadParams = new VideoUploadParams()
{
  File = new FileDescription(@"my-video"),
  Type = "upload",
  EagerTransforms = new List<Transformation>()
  {
    new EagerTransformation().SetFormat("webm").Effect("vignette").Border("5px_solid_black").Chain()
      .VideoCodec("vp9"),           
    new EagerTransformation().SetFormat("mp4").Effect("vignette").Border("5px_solid_black").Chain().
      VideoCodec("h265"),           
    new EagerTransformation().SetFormat("mp4").Effect("vignette").Border("5px_solid_black")         
  },
  EagerAsync = true,
  EagerNotificationUrl = "https://mysite.example.com/eager_endpoint"
};
var uploadResult = cloudinary.Upload(uploadParams);

The example code above processes the eager transformations asynchronously and sends a notification to the defined URL once complete and ready for delivery.

Rather than defining the required eager transformations in your code, you could make use of upload presets instead, allowing you to define the matching eager transformations once and use this for all uploads. This means that if you need to change your video player configuration, you would only need to update your upload preset configuration and your code would still generate the correct URLs.

You can create your upload preset using the Cloudinary console or alternatively you can do this programmatically.

Once you have your upload preset, you can use it with your upload code as shown below.

Ruby:
Copy to clipboard
Cloudinary::Uploader.upload(my-video, "my-upload-preset")
PHP (cloudinary_php v2.x):
Copy to clipboard
$cloudinary->uploadApi()->upload(my-video, "my-upload-preset")
PHP (cloudinary_php v1.x (legacy)):
Copy to clipboard
\Cloudinary\Uploader::upload(my-video, "my-upload-preset");
Python:
Copy to clipboard
cloudinary.uploader.upload(my-video, "my-upload-preset")
Node.js:
Copy to clipboard
cloudinary.v2.uploader.upload(my-video, "my-upload-preset");
Java:
Copy to clipboard
cloudinary.uploader().upload(my-video, "my-upload-preset");
.NET:
Copy to clipboard
cloudinary.Upload(UploadParams params);

✔️ Feedback sent!

Rate this page: