相关文章推荐

Video Player API reference Last updated: Apr-19-2024

Modules

When importing the player as a module , any additional functionality will require the relevant module and css (where required) be included, for example:

The available modules are:

Chapters - chapters DASH adaptive streaming - dash Ads - ima Interactive videos - interaction-areas Playlists - playlist Recommendations - recommendations-overlay Shoppable videos - shoppable

Configuration options

You can define many of the player configuration options either as attributes of the <video> tag or as constructor parameters of the videoPlayer or videoPlayers method. These settings are the default for all videos that play in the player(s), but are overridden if a specific video source has a different value for the same setting.

This section includes:

  • Constructor parameters
  • Constructor types
  • Constructor enums
  • Video tag attributes
  • For an overview and instructions on setting configuration parameters, see the configuration step of 'How to embed the video player'.

    Constructor parameters

    Use constructor parameters of the videoPlayer or videoPlayers method to define global configuration options.

    You can control:

    Player visuals - how the player looks. Player behavior - how the player behaves. Video config - configuration for the video itself. Ads and analytics - how the player handles ads and analytics. Shoppable Video - configuration for adding Shoppable Video components to the player.

    Player visuals

    Param Description aiHighlightsGraph Boolean Whether to show an AI-generated visual representation of the highlights of a video. Default: false
    Note : When the graph is first generated, additional transformations are used and it may take a short time to complete. bigPlayButton Boolean or String Whether to show a larger central play button when the video is paused.
    Possible values:
    - true : Always show big play button.
    - false : Never show big play button.
    - init : Show big play button on initial load only.
    Default: true chaptersButton Boolean Whether to show the chapters button, which opens a list of chapters. Default: false colors Object The colors to use for the player UI. The values must be supplied as hex color codes. You can set:
    - base : The base color for the player's controls and information bars as well as the base color of the central play button.
    - accent : The color for the progress bar and volume level.
    - text : The color for all text and icons. controlBar ControlBarProps Configuration for components of the control bar. controls Boolean Whether to display the video player controls. floatingWhenNotVisible FloatingWhenNotVisible Whether to display a floating player in the corner of the screen when a video is playing and less than half the player is visible.
    Possible values:
    - right : Shows floating player in the bottom right of the screen
    - left : Shows floating player in the bottom left of the screen fluid Boolean Whether to activate fluid layout mode, which dynamically adjusts the player size to fit its container or window.

    Note : You can alternatively pass cld-fluid as a css class of the video tag. For example:
    class="cld-video-player cld-video-player-skin-dark cld-fluid"

    fontFace FontFace The font to use for text elements in the video player. If not specified, the player loads with the default player font-family: Fira Sans. hideContextMenu Boolean Whether to hide the context menu that appears when right-clicking on the player. Default: false interactionAreas interactionAreas Configuration for adding areas of interaction to the video player. Allows the viewer to click on the video and interact with it, for example zooming in on an area of the video. For more information, see Interactive Video . pictureInPictureToggle Boolean Whether to display the picture-in-picture toggle to allow users to view videos in a floating window. Default: false playbackRates Array An array of playback rates to display in the control bar. Allows the user to change the speed that the video plays at. playlistWidget PlaylistWidgetProps Adds a playlist widget to the video player. posterOptions Object A default poster that is shown every time a new video loads. It can include transformation settings. By default, every new video that loads will use the middle image of that video ( /video/publicId.jpg ) and if the player width is set, the poster will be responsive. For example, to set the sample image with a sepia effect as the fixed poster image for all videos: posterOptions: { publicId: 'sample', effect: ['sepia'] } seekThumbnails Boolean Whether to display thumbnails of the video when seeking with the seek bar. Default: true
    Note : When seek thumbnails are generated, an image sprite containing all the thumbnails is automatically created. As such, this will use an additional
    transformation and may take a short time to complete. videoJS Object Enables you to access all underlying capabilities of the VideoJS API. For details, see the VideoJS Player API .

    Player behavior

    Param Description autoplay Boolean Whether to apply standard HTML5 autoplay. Default: false .
    Note : autoplay behaves differently on different browsers and devices. See the relevant browser documentation for more information. autoplayMode AutoplayMode The autoplay mode to use for the player. Similar to the default HTML5 autoplay parameter, but with the addition of on-scroll support. Default: never . autoShowRecommendations Boolean Whether to show recommendations at the end of the current video, if available. For playlists where autoAdvance is false , the next videos are automatically used as the recommendations, if none are explicitly defined. For players with a single source, in addition to setting autoShowRecommendations to true , you must explicitly define the videos to recommend using the source.recommendations parameter. You can also optionally use the source.recommendations parameter for sources in a playlist, which overrides the default behavior of showing the next videos as recommendations. Boolean Whether to perform standard HTML5 video looping. Default: false . maxTries Number The maximum number of times the video player will attempt to request a video. Multiple requests may be necessary if the video is still being processed when it is first requested. Default = 3 . Can be used in conjunction with videoTimeout . muted Boolean Whether the player loads in standard HTML5 mute mode. Default: false . playedEventPercents Array An array listing percentage points for which you want to trigger the percentsplayed event. Default: [25, 50, 75, 100] . playedEventTimes Array An array listing times (in seconds) from the beginning of the video for which you want to trigger the timeplayed event. Default: null . playsinline Boolean Relevant for iOS only. Whether the video should be prevented from entering fullscreen mode automatically when playback begins. Can be used with autoplay and muted to enable autoplay on iOS devices. videoTimeout Milliseconds The maximum time the video player will wait for a video to be available in each video request. This may be relevant if the video is still being processed when it is first requested. Default = 55000 . Can be used in conjunction with maxTries . withCredentials Boolean Whether to include the withCredentials header when the player makes an XHR request, such as for manifest files or video segments. The withCredentials header includes any authentication headers or cookies from the browser when making a request.

    Video config

    Param Description chapters Object The chapters defined for the player when the publicId constructor parameter is set. In most cases, it's a better practice to specify the chapters as part of the videoPlayer.source method. preload String The type of standard HTML5 video preloading to use. Relevant only when autoplay is false or autoplayMode is never .

    Possible values:

    • auto : Default. Begin loading the video immediately.
    • metadata : Only load the video metadata.
    • none : Don't load any video data.
    • Array The video source types (and optionally the corresponding codecs) that will be available for the player to request (as appropriate for the current browser). If a source type can't be played in the requesting browser, the next source in the array will be tried. Add the codec after the source type and separate with a '/', for example: mp4/h265 .

      For HLS and MPEG-DASH, use the values hls and dash respectively and optionally specify a codec as described above.

      For automatic format selection , use auto .

      For audio only, use audio .

      If you also define a codec as part of a transformation, this will override the source type.

      Default: f_auto:video . By default, automatic format selection is applied, which selects the optimal file type based on the user's device and browser. transformation cloudinary.Transformation, Object, Array, or String Default transformation to apply on every source video that plays in the player.

      Ads and analytics

      Param Description AdsProps Enables serving ads in your video player based on leading video ad standards such as VAST, VPAID, and VMAP, including Google DoubleClick or AdSense. For more details, see Video ads and monetization . analytics Boolean Whether to activate analytics for video player events. Default: false . allowUsageReport Boolean Cloudinary can optionally collect aggregated statistics about how the video player is being used. The collected data is used in aggregate form to help us improve future versions of the video player and cannot be used to identify individual video viewers. When true (default), Cloudinary collects data on events performed by the video player. cloudinaryAnalytics Boolean Whether to send video analytics data to Cloudinary. Default: true .

      Constructor types

    • AdsProps
    • PlaylistWidgetProps
    • AdsProps

      Param Description showCountdown Boolean Optional. When true, the 'Advertisement' countdown label is displayed in small text in the bottom center of the video player along with a counter showing the time (in seconds) until the end of the video. Default: true . adLabel String Optional. Alternative or translated text for the 'Advertisement' countdown label. Relevant only when showCountdown is true. locale String Optional. Locale for ad localization. Can be any ISO 639-1 (two-letter) or ISO 639-2,(three-letter) locale code. This setting affects the language of relevant elements within the adTag, such as the Skip option. Default: en . prerollTimeout Number Optional. Maximum time (in milliseconds) to wait for a preroll ad to start. If the ad does not start an adtimeout event is triggered. postrollTimeout Number Optional. Maximum time (in milliseconds) to wait for a postroll ad to start. If the ad does not start an adtimeout event is triggered. horizontal Displays the thumbnails of upcoming videos horizontally. The widget is located below the player and is in addition to the dimensions defined for the player. vertical Displays the thumbnails of upcoming videos horizontally. The widget is located to the right of the player and is displayed inside the dimensions defined for the player (the video is resized accordingly).

      Video tag attributes

      Cloudinary attribute parameters are passed as part of the <video> tag in the format data-cld-<configname> . Complex objects are passed as JSON. The attributes listed below have the same descriptions, possible values and defaults as the parallel JavaScript video player constructor parameters listed above.

      In addition to the Cloudinary-specific configurations, All HTML5 constructor attributes can be passed as HTML tag attributes as usual.

      The following Cloudinary attribute parameters are supported. An example for each is shown:

    • data-cld-transformation='{ "width": 200, "crop": "limit" }' 
    • data-cld-poster-options='{ "publicId": "sample", "effect": ["sepia"] }' 
    • data-cld-source='{ "publicId": "mymovie", "transformation": { "width": 500 } }'
    • data-cld-source-types='["mp4", "ogg", "webm"]'
    • data-cld-source-transformation='{ "mp4": { "width": 410 } }'
    • data-cld-public-id="mymovie" 
    • data-cld-autoplay-mode="on-scroll" 
    • data-cld-floating-when-not-visible="left"
    • data-cld-font-face="Yatra One" 
    • data-cld-colors="{ "base": "#eef9ee", "accent": "#00e64c", "text": "#009688" }" 
    • Instance methods

      The video player methods below enable you to get or set properties, or perform operations on your player after the initial instance loads.

      Most of the methods return the player instance, so you can chain method calls.

      For example, the following code creates a playlist for the player and then calls the play method:

      And this code mutes the player, sets a transformation that applies to all sources in that player, sets the source video for the player and then calls the play method:

      You can use the instance methods for:

      Video configuration - configure the video source, playlists and transformations. Controls - handle basic video controls such as playing, pausing and adjusting the volume. Video player element - configure the video player element itself.

      Video configuration

    • currentPublicId
    • source
    • playlist
    • playlistByTag
    • sourcesByTag
    • autoShowRecommendations
    • sourceTypes
    • sourceTransformation
    • transformation
    • posterOptions
    • currentPublicId

      currentPublicId()

      Use the currentPublicId method to get the current source's Cloudinary public ID.

      source

      source(publicId or rawUrl,options)

      Use the source method to set a new video source for the player and configure it. Configure the new videoSource using the following as constructor parameters. You can also get or set these as properties or operations on your videoSource object after the initial instance loads.

      publicId

      The Cloudinary public ID of the video to play. Can be specified as a standalone parameter or within the options parameter.

      rawUrl

      The full URL of the video to use as the source. If specifying a Cloudinary URL, you can include transformations within the URL as an alternative to defining them as part of the options parameter.

      Notes
    • When using raw URLs, you must include the cloud name of the relevant Cloudinary product environment when creating your video player instance to support video analytics data.
    • Any transformations included in the URL will overwrite any defined using the options parameter.
    • options
      Param Description Boolean or Object The chapters defined for the video source. Can be added by:
      • Setting to true for adding chapters automatically from a VTT file stored in your product environment using the naming convention <public id>-chapters.vtt . Can be created using the chapters editor in the video player studio
      • Specifying a link to a VTT file using the url parameter
      • Defining the chapters manually by setting the key as the chapter start time in seconds and the value as the chapter title.
      For example:
        chapters: true
      • chapters: { url: "https://res.cloudinary.com/demo/raw/upload/docs/chapters_example.vtt" }
      • chapters: { 1: "Chapter 1", 6: "Chapter 2", 12: "Chapter 3" }
      Default: false Object The title, subtitle, and description of the video, used in the main player view, upcoming video for playlists, and the recommendations pane. For example: vplayer.source('mymovie', {info: { title: 'My Title', subtitle: 'Something about the video', description: 'More detail about the video' } }) interactionAreas Object Configuration for adding areas of interaction to the video player for the specified source. Allows the viewer to click on the video and interact with it, for example zooming in on an area of the video. For more information, see Interactive Video . maxTries Integer The maximum number of times the video player will attempt to request a video. Multiple requests may be necessary if the video is still being processed when it is first requested. Default = 3 . Can be used in conjunction with videoTimeout poster Object The poster to show while the video source is loading. Default: the middle image of the source video ( /video/publicId.jpg ) recommendations Array, Function, or Promise The videoSource objects to be shown as recommendations for the current videoSource . Can be specified as an array of sources, or a function or Promise that resolves into an array of sources. See showing video recommendations for more. shoppable Object Configuration for adding components to the video player UI for the specified source. Allows the viewer to click on items for purchase. For more information, see Shoppable Video . sourceTypes Array The video source types (and optionally the corresponding codecs) that will be available for the player to request (as appropriate for the current browser). If a source type can't be played in the requesting browser, the next source in the array will be tried. Add the codec after the source type and separate with a '/', for example: mp4/h265 .

      For HLS and MPEG-DASH, use the values hls and dash respectively and optionally specify a codec as described above.

      For automatic format selection , use auto .

      For audio only, use audio .

      If you also define a codec as part of a transformation, this will override the source type.

      Default: f_auto:video . By default, automatic format selection is applied, which selects the optimal file type based on the user's device and browser. sourceTransformation Object Default transformations to apply to a specific source type. For example: vplayer.source('mymovie'), {sourceTransformation({ 'mp4': { width: 410 }}}) . See sourceTransformation method for syntax. textTracks Object The text tracks to add to the video source, used to add subtitles or captions .

      For example: player.source('outdoors', {textTracks: { captions: { label: 'English captions', language: 'en', default: true, url: 'https://res.cloudinary.com/demo/raw/upload/outdoors.vtt'} } })

      Use the options parameter to specify customization options .

      transformation cloudinary.Transformation, Object, Array or String The transformation to apply on the specified video source. See transformation method for syntax. videoTimeout Integer The maximum time (in milliseconds) that the video player will wait for a video to be available in each video request. This may be relevant if the video is still being processed when it is first requested. Default = 55000 . Can be used in conjunction with maxTries . fontSize String The font size to use for your text tracks. Use relative units only, such as % or em . gravity String The position of the text tracks on the video or in the containing box . Supports the directional values top , right , bottom , left , center , and their combinations: top-right , bottom-right , bottom-left , top-left . Default: bottom style Object CSS styling to apply to the text. For example: {color: black} . theme String A set of predefined styles to apply to the text tracks. Possible values: default , videojs-default , yellow-outlined , player-colors , 3d . Default: default .

      playlist

      playlist(sources,options)

      Use the playlist method to get or set a list of video sources to play in the player, including any required transformations.

      sources

      The video sources to play in the playlist, see source for more information.

      options
      Param Description Number or false Whether to auto-advance to the next video and the delay between them.
      Possible values:
      - 0 : Advance Immediately.
      - Any positive value : Delay in seconds between videos.
      - false : Do not advance repeat Boolean Whether to loop back to the first video after the last video in the playlist ends. presentUpcoming Boolean Whether to display a thumbnail link of the next video in the list when the current video is almost finished.
      Possible values:
      - false : Default. Do not present upcoming videos.
      - true : Present upcoming videos 10 seconds before the end of the current video.
      - Any positive value - Seconds before the end of the current video to show the upcoming video.

      You can also change these options and perform many other operations on the playlist instance after the player is created. For details, see: Playlist operations .

      playlistByTag

      playlistByTag(tag,options)

      Use the playlistByTag method to perform a call to the client-side asset list operation and return a promise object that when fulfilled, returns the player with a playlist comprised of all videos in your product environment with the specified tag.

      String value representing the tag name with which to build the playlist from.

      options
      Param Description sorter Function By default, the video list is sorted in the order returned by Cloudinary. This parameter receives a function that sets the order of the retrieved video sources. Your function should receive two entries and determine which one comes first. This sorter behavior works similarly to the JavaScript array CompareFunction . sourceParams Object Source settings that will apply to all retrieved videos. autoAdvance Number or false Whether to auto-advance to the next video and the delay between them.
      Possible values:
      - 0 : Advance Immediately.
      - Any positive value : Delay in seconds between videos.
      - false : Do not advance repeat Boolean Whether to loop back to the first video after the last video in the playlist ends. presentUpcoming Boolean Whether to display a thumbnail link of the next video in the list when the current video is almost finished.
      Possible values:
      - false : Default. Do not present upcoming videos.
      - true : Present upcoming videos 10 seconds before the end of the current video.
      - Any positive value - Seconds before the end of the current video to show the upcoming video.

      sourcesByTag

      sourcesByTag(tag,options)

      Use the sourcesByTag method to retrieve the (promise of) the video sources for a specified tag without actually creating the playlist. This method has the same syntax and supports the same options as the playlistByTag .

      autoShowRecommendations

      autoShowRecommendations(Boolean)

      Use the autoShowRecommendations boolean method to determine whether to show recommendations at the end of the current video, if available. For playlists where autoAdvance is false , the next videos are automatically used as the recommendations, if none are explicitly defined. For players with a single source, in addition to setting autoShowRecommendations to true , you must explicitly define the videos to recommend (or provide a function or Promise that returns and array of sources) using the source.recommendations parameter. You can also optionally use the source.recommendations parameter for sources in a playlist, which overrides the default behavior of showing the next videos as recommendations.

      sourceTypes

      sourceTypes(Array)

      Use the sourceTypes method to get or set the default source types (and optionally the corresponding codecs) that will be used for every video. If a source type can't be played in the requesting browser, the next source in the array will be tried. Add the codec after the source type and separate with a '/', for example: mp4/h265 .

      For HLS and MPEG-DASH, use the values hls and dash respectively and optionally specify a codec as described above.

      For automatic format selection , use auto .

      For audio only, use audio .

      If you also define a codec as part of a transformation, this will override the source type.

      Default : Default: f_auto:video . By default, automatic format selection is applied, which selects the optimal file type based on the user's device and browser.

      sourceTransformation

      sourceTransformation(Object)

      Use the sourceTransformation method to set the default transformation that will be used for all videos of the specified source type.

      To get the transformation set for a particular source type, use:

      transformation

      transformation(cloudinary.Transformation, Object, Array or String)

      Use the transformation method to get or set the base transformation of the player.

      posterOptions

      posterOptions(options)

      Use the posterOptions method to get or set the public ID and/or transformation to apply from now on when a new video loads. By default, every new video that loads uses the middle image of that video ( /video/publicId.jpg ).

      options
      Param Description transformation cloudinary.Transformation, Object, Array or String The transformation to apply on the specified video source. See transformation method for syntax posterColor string A constant color to display instead of an image. Not relevant if also including the publicId or transformation parameters in the posterOptions object. The color can be a string value representing an RGB or RGBA hex triplet or quadruplet, a 3- or 4-digit RGB/RGBA hex, or a named color.

      stop()

      Use the stop method to stop the current video (Same as Pause + set currentTime to 0).

      playNext

      playNext()

      Use the playNext method to play the next video in the playlist.

      playPrevious

      playPrevious()

      Use the playPrevious method to play the previous video in the playlist.

      volume

      volume(volume)

      Use the volume method to get or set the video player volume level. The volume is a value between 0 (muted) and 1 (max volume).

      mute()

      Use the mute method to mute the video player.

      unmute

      unmute()

      Use the unmute method to unmute the video player and revert the previous volume level.

      isMuted

      isMuted()

      Use the isMuted method to return whether the player is currently muted.

      currentTime

      currentTime(offsetSeconds)

      Use the currentTime method to get or set the current time of the video that is playing.

      duration

      duration()

      Use the duration method to return the duration of the currently playing video.

      maximize

      maximize()

      Use the maximize method to enter fullscreen mode.

      exitMaximize

      exitMaximize()

      Use the exitMaximize method to exit fullscreen mode.

      isMaximized

      isMaximized()

      Use the isMaximized method to return whether video player is in full screen.

      Video Player element

    • fluid
    • height
    • width
    • dispose
    • videoJS
    • fluid

      fluid(Boolean)

      Use the fluid method to determine whether to responsively resize the video to fit the size of its container or window.

      height

      height(dimension)

      Use the height method to get or set the video player's height.

      width

      width(dimension)

      Use the width method to get or set the video player's width.

      dispose

      dispose()

      Use the dispose method to dispose the video player and remove its element from the DOM.

      Use the el method to return the video player DOM element.

      on(event, callback)

      Use the on method to register an event handler to the specified event.

      off(event, callback)

      Use the off method to unregister an event handler from the specified event.

      videoJS

      videoJS(Object)

      Use the videoJS method to enable you to access all underlying capabilities of the VideoJS API. For details, see the VideoJS Player API .

      Events

      You can register to video player events and then use these events to create custom video player controls or to trigger other custom behaviors in your application.

      Additionally, some of these events can be tracked for Google Analytics or other analytics trackers.

    • For an overview and instructions on working with video player events, see Using video events
    • For information on tracking analytics data using events, see Tracking video player analytics .
    • You can register event handlers to the following standard HTML5 Video events:

      loadstart , suspend , abort , error , emptied , stalled , loadedmetadata , loadeddata , canplay , canplaythrough , playing , waiting , seeking , seeked , ended , durationchange , timeupdate , progress , play , pause , ratechange , volumechange , fullscreenchange , posterchange .

      Additionally, the following events are also available for the Cloudinary Video Player:

    • unmute
    • percentsplayed
    • timeplayed
    • sourcechanged
    • qualitychanged
    • Triggered when player is muted.

      unmute

      Triggered when player is unmuted.

      percentsplayed

      Triggered when video playback reaches X percent out of the total video duration. The percents that trigger this event defined by the video player constructor's playedEventPercents parameter.

      timeplayed

      Triggered when video playback reaches X seconds after the beginning of the video. Seconds are defined by the video player constructor's playedEventTimes parameter.

      Triggers seekStart and seekEnd data.

      sourcechanged

      Triggered when the video player source changes.

      qualitychanged

      Triggered when the adaptive bitrate quality changes. Returns the video height and width that the player changed from and to.

      Errors

      You can listen for any errors with the error event. You can then use the response from the error to determine how the video player should respond. For example, the function below shows a custom error message in the video player:

      Playlist operations

      You can create a playlist for your player based on a list of public IDs or for all videos with a specified tag. Use the methods below to control your playlist.

      For an overview and instructions on creating a playlist, see Creating a playlist .

      Operation Description playAtIndex(index) Sets the player's current video source as the one located at the specified 0-based index location in the playlist and starts playing it. currentIndex(index) Gets or sets the current video source 0-based index value. currentSource() Gets the currently playing videoSource . list() Gets an array of videoSource instances for the playlist. repeat(repeat) Gets or sets whether the playlist will replay the playlist from the beginning after the last video finishes playing. playFirst() Sets the player's current video source to the first video source in the playlist and plays it. playLast() Sets the player's current video source to the last in the playlist and plays it. length() Returns the number of video sources in the playlist. playNext() Sets the player's current source to the next source in the playlist and plays it. If the currently playing source is the last one in the list and repeat is set to true , the first source in the list plays. Otherwise, nothing happens. playPrevious() Sets the player's current source to the previous source in the playlist and plays it. If the currently playing source is the first one in the list, nothing happens. player() returns the videoPlayer for this playlist. autoAdvance(delay) Gets or sets the autoAdvance configuration for the playlist.
      - A positive integer delay value sets the delay in seconds that the player will wait before playing the next video.
      - A value of false cancels auto advance. (To move to the next video use playNext ).
      - A value of 0 causes the next video to play immediately after the previous one finishes. presentUpcoming Gets or sets the presentUpcoming configuration for the playlist.
      - A value of false cancels presentation of upcoming videos.
      - A value of true activates presentation of upcoming videos 10 seconds before the end of the current video.
      - A positive integer value sets the number of seconds before the end of the current video to show the upcoming video. Cloudinary is committed to protecting your information security. For details, see our privacy policy . For additional assistance, open a support request .

      Error

      Unfortunately there's been an error sending your feedback.

     
    推荐文章