Categories: Thủ Thuật Mới

Mẹo Autoplay true Mới nhất

Mục lục bài viết

Kinh Nghiệm Hướng dẫn Autoplay true Chi Tiết

Update: 2022-03-01 21:15:14,Bạn Cần biết về Autoplay true. Quý khách trọn vẹn có thể lại Thảo luận ở phía dưới để Tác giả đc lý giải rõ ràng hơn.


The Dailymotion Player is a state-of-the-art video player built with the latest web technologies (HTML5/JavaScript) and video standards (HLS adaptive streaming).

Tóm lược đại ý quan trọng trong bài

  • Embed the player on web
  • Getting started
  • Player Embed Script
  • Player iFrame
  • Embed the player in native apps
  • Android SDK
  • Embed the player on AMP
  • Customize the player
  • Working with player settings
  • Working with player parameters
  • Working with autostart
  • Working with TCF2
  • JavaScript Player API Reference
  • JavaScript Player API Reference (legacy)
  • Methods (legacy)
  • Events (legacy)
  • Player Properties (legacy)
  • Player Parameters (legacy)

Its easy to use, cross-platform friendly and enjoyed by millions of users every day both on Dailymotions properties and hundreds of our premium Partners websites and native applications.

The Player is customizable, consistent across all devices, delivered with Picture-in-Picture, extensive analytics and the necessary advertising infrastructure out of the box.

We have opened a CodePen developer account to provide access to some code samples that will allow you to discover the Dailymotion Player and its features, check it outhere.

Depending on your needs you can integrate the Player using one of the methods outlined below. We recommend where possible to embed using one of the libraries in order to take full advantage of our Player technology.

IntegrationInfoAccess to Player APIPlayer Embed ScriptEmbed using JavaScript, the single line script will load the Player at the point where you add it to the HTML pageYesPlayer Library ScriptAdd just the player JavaScript library to create players programmaticallyYesPlayer iFrameThe iFrame embed method is the most basic way to integrate the Player. Advanced functionality such asPiPandfirstTimeViewwill not be availableNoAndroid SDKThe SDK is a thin wrapper around a WebView that allows to easily embed the Player into an Android applicationYesiOS SDKA Swift wrapper around the WKWebView Class that allows developers to easily embed the Player in iOS applicationsYesAmpThe Dailymotion AMP component is available to embed the Player with the AMP frameworkNo

Embed the player on web

Embedding the player on your properties is simple. There are different integration methods available depending on your technical preference or environment. We recommend using one of the script embeds type where possible as it provides access to all player functionality and the Player API.

Embed typeInfoPlayer Embed ScriptEmbed using JavaScript, the single line script will load the Player at the point where you add it to the HTML page. This also provides access to the Player APIPlayer Library ScriptAdd just the library and create the player programmatically using the Player APIPlayer iFrameEmbed the player without JavaScript to use a basic player configuration. Advanced functionality such asPiPandfirstTimeViewwill not be available

Getting started

As a first step you need to create a custom player configuration associated with your Dailymotion account and defined by a unique Player Id. This identifier is required to ensure accurate monetization, targeting and attribution.

  • Create a custom player configuration
  • A custom player configuration can be created and managed either through the Players tab in the Partner Space or programmatically via the playerREST API.

    A Player configuration is composed of several settings. These settings cant be modified or overridden at run time. They can only be updated via the player configurator in the Partner Space or the Player REST API.

    For more information on the settings that are available, please refer to the sectionPlayer settings.

  • Add the Player or Player library
  • Once a Player configuration is created you can access the corresponding scripts that can be embedded into your properties. Embed scripts can be accessed either from the Players tab within the Partner Space or programmatically via the player REST API.

    The following integration types are available to use the Player on the web:

    Embed typeInfoPlayer Embed ScriptEmbed using JavaScript, the single line script will load the Player at the point where you add it to the HTML page. This also provides access to the Player APIPlayer Library ScriptAdd just the library and create the Player programmatically using the Player APIPlayer iFrameEmbed the player without JavaScript to use a basic player configuration

    Player Embed Script

    The Player Embed Script integration method is the easiest way to embed the Player with the library on your site and provides access to the Player API. It is a single-line script that loads the Player exactly where it is added into theof the page.

    Embed a video

    After adding the Player embed script, use thedata-videoattribute to specify which video ID to load. It should be added directly to thescripttag that loads the pre-configured Player. To ease integration its already added to the embed script that can be copied via the Partner HQ and requires only a video Id to be defined.

    After adding the Player embed script, use thedata-playlistattribute to specify which playlist ID to load. It should be added directly to thescripttag that loads the pre-configured player.

    To use multiple Player configurations on a single page just add different embed scripts specifying their unique Player IDs.

    The Player library script is available for developers who want to load just the library, the Player can be then loaded programmatically via the Player API. The Player library URL can be either copied from the Partner HQ in the Players tab or retrieved from the REST API (seelib_script_urlfield).

    Any Player created with the Player API will carry over the configuration corresponding to the Player ID embedded in the Player library script. Additional player configurations can be specified in thecreatePlayer()method using theplayerparameter.

    It takes only 3 steps to load our player using the Player library script:

  • Add the Player library script to your HTML page
  • Add the library script within thesection of the page. This provides access to the Player API and allows you to create a Player instance programmatically. It should be added before any code that interacts with the Player API is loaded.

  • Add a placeholder for the player
  • Add adivplaceholder on the page where you want the player(s) to be loaded and assign an id to the container which will be required in the createPlayer() method.

    My Player placeholder
  • Create the Player using the Player API
  • Use thecreatePlayer()method and pass in the assigned container id to initialize the player, specify the video, playlist and parameters to be loaded. You can also specify a player configuration to use with theplayerattribute in order to load a different player configuration, by default the configuration of the embedded library will be applied.

    It is recommended when adding only one single Player on a page, allow for the Player configuration to be specified in thelib_script_urlrather than thecreatePlayer()method.

    My Player placeholder

    dailymotion
    .createPlayer(“my-dailymotion-player”,
    video: “x84sh87”,
    )
    .then((player) => console.log(player))
    .catch((e) => console.error(e));

    Embed a video

    After loading the Player Library script use thecreatePlayer()method and pass in the container id to initialize the Player and specify the video to be loaded. The Player configuration specified in the embedded library script will apply to every created player.

    The video must be specified using thevideoattribute.

    Use thecreatePlayer()method and pass in the container id to initialize the player as well as the playlist Id to be loaded.. The Player configuration specified in the embedded library script will apply to every created player.

    The playlist must be specified using theplaylistattribute.

    Any Player created with the Player API will carry over the configuration corresponding to the embedded Player library script.

    If it is required to load multiple Players with different configurations on a single page, other Player IDs can be specified in thecreatePlayer()method using the’player’parameter. Therefore any number of Player configurations can be embedded with only a single-Player library URL.

    If the Player ID is incorrectly specified or does no longer exist the configuration will fall back to a default library configuration. If multiple player scripts are loaded on a page but no player is specified via the createPlayer() method, an error will be logged and the created player will take a default config.

    Player iFrame

    Embed a partially configured player without JavaScript. Smart player functionality such as Picture-in-Picture, first time viewable and auto-sizing along with access to the Player API wont be available. The iFrame Player will benefit only from basic UI customizations specified in the Player configurator UI or Rest API. We recommend partners take full advantage of our Player technology and use thePlayer embed scripts.

    Embed the player in native apps

    We provide our publishers with the same tools we use to create our flagship Dailymotion applications: the same Player and the same SDKs. Check out our apps in theApple App StoreorGoogle Play Storewhich have over 50M+ downloads.

    Our Mobile SDK provides access to the Player API and gives you full control of the player. Along with having a genuine native feel, its possible to use our provided tools, to build a unique video solution in your app, benefiting from your own custom UI components and aligning it with the look and feel of your brand.

    As our SDKs are open source, partners can make a pull request to update the iOS or Android SDK. Please check the source code, documentation and sample app onGitHub.

    IntegrationInfoAccess to Player APIAndroid SDKThe SDK is a thin wrapper around a WebView that allows you to easily embed Dailymotion videos into your Android applicationYesiOS SDKA Swift wrapper around the WKWebView class that allows developers to easily embed the Dailymotion Player in their appYes

    Android SDK

    The SDK is a thin wrapper around a WebView that allows to easily embed Dailymotion videos into your Android application. We recommend using the SDK rather than the video URL in a standard webView, as it gives you more controls of the player and its better for tracking purposes. Our Android SDK is open source and you can get all the required information plus a sample app on ourGitHub.

    The SDK supports Android 5.0.x (API level 21+) and It is fully in Kotlin, If your project is still in JAVA, please add the Kotlin dependencies:developer.android/kotlin/add-kotlin.

    How to use:

  • The easiest way to integrate the SDK is by adding it to your applicationbuild.gradlefile.
  • ThePlayerWebViewis the main SDK component that allows you to load videos easily into your android environment. Add the component to the selected layout which will display the player. To load the video without autoplay, you can use thesetPlayWhenReady(false)method
  • Initialize the player in your selected activity, reference the PlayerWebView and use one of the load methods available. You can use theload()method, which will initialize a default player config, load the player and start playing the selected video. Or it is also possible to use theinitialize()method to load the player with a custom config using any available player params.
  • lateinit var playerWebView: PlayerWebView override fun onCreate(savedInstanceState: Bundle?)
    super.onCreate(savedInstanceState) setContentView(R.layout.screen_sample);
    playerWebView = findViewById(R.id.playerWebview)
    val params = mapOf(“video” to “x84sh87”)
    playerWebView.load(loadParams = params);

    In order to customize the player, pass in player parameters to your player instance. Create aMapinterface, add an entry of the chosen player parameters into the map along with its associated value, then pass theMapinto theinitialize()method. To load multiple videos while keeping the same player instance and config, use theload()method after player initialization.

    val params = mapOf(
    “ui-highlight” to “fff”,
    “logo” to “false”
    )
    dailymotionVideoPlayer.initialize(“dailymotion/embed/”, params = params, emptyMap())

    Player Parameters for Android SDK

    Use the below parameters to customize your player via the iframe or SDK embed.

    ParameterInfoTypeautoplayAutomatically attempt to start playback with sound, if it is blocked by the browser, the player will force the video muteBooleancontrolsWhether to display the player controls, true by defaultBooleanidID of the player unique to the page to be passed back with all API messagesStringmuteWhether to mute the videoBooleanqualitySpecify the suggested playback quality for the videoNumbersharing-enableWhether to display the sharing buttonBooleanstartSpecify the time (in seconds) from which the video should start playingNumbersubtitles-defaultSpecify the default selected subtitles languageStringsyndicationPass your syndication key to the playerStringui-highlightChange the default highlight color used in the controls (hex value without the leading #). Color set in the Partner HQ will override this paramStringui-logoWhether to display the Dailymotion logoBooleanui-start-screen-infoWhether to show video information (title and owner) on the start screenBooleanplaylistSpecify a playlist ID to populate the Up Next Queue with videos from a playlistStringfullscreenWhether to display the fullscreen buttonBooleanscaleModeSpecify the default focus of the player in order to reframe and refocus on a specific area in the video. To be used for scaling and repurposing of videos between different aspect ratios for example landscape to portrait. Values ( fit, fill, fillLeft, fillRight, fillTop, fillBottom )StringloopWhether to loop a video or an entire playlist. A video embed will start over again automatically. A playlist embed will start to play from the first item in the playlist after the entire playlist has finishedBooleanMethods

    Once the SDK and the Player are loaded you can use the Player API to control the player. You have full access to all player methods and there are also methods supplied in the Android SDK that return specific player properties.

    dailyMotionVideoPlayer.pause();

    NameInfoload(String)Calls the initialize method, loads the player with a video associated with the video id (e.g. x7tgad0)initialize(String, Map, Map)Loads the player with base string URL of playerhttps://dailymotion/embed/ accompanied by a MAP interface of required player parameter valuesfinishedInitialization (String, Map, Map)Loads the player with a given URL, parameters and advertising IDplay()Starts or resumes video playbackpause()Starts or resumes video playbacksetFullScreenButton(Boolean)Enters fullscreen mode when true and controls player fullscreen button state. The method should be utilized in association with the native fullscreen functionality in appsetPlayerEventListener(Eventlistener)Add a listener which will be called when the Android system WebView can an errorunmute()Unmute the playermute()Mute the playercallPlayermethod(String, Object)Call a method from the Js Player API, if not already exposed in the Android SDKsetPlayWhenReady(Boolean)Set the autoplay behavior of the player when video is loaded. Set to true, for autoplay enabled.setQuality(String)Set player to play at a specified quality if available[240, 380, 480, 720, 1080, 1440, 2160 default]setSubtitle(String)Activate subtitles track to a specified language if availablesetVolume(float)Set the players volume to the specified level between 0 & 1. ie, 0.5 = 50%release()Destroy the Player webViewseek(double)Seek to the specified time in video playback in secondssetIsWebContentDebuggingEnabled()Enable the Android system WebView debug modesetMinimizeProgress(float)Disable the player UI when set to 0, enables when 1setWebViewErrorListener(WebViewErrorListener)Add a listener for Android system WebView errorshowControls()Enable the display of the player UItoggleControls()Turn on/off the players UI componentstogglePlay()Switch between player & pause

    In order to make a developers life easier, we created methods in our android SDK that will return the value of a specific player property. Not all player properties are returned by a set method, some are returned in the payload sent after the player sự kiện, please seeherefor more info about events.

    NameInfogetBufferedTime()Returns a Double Number. The part of the truyền thông resource that has been downloaded in secondsgetVideoPaused()Returns a boolean value for current pause state of the playergetVolume()Returns a float value for the volume property between 0 and 1isEnded()Returns a boolean value for whether the truyền thông resource has endedisSeeking()Returns a boolean value for whether the video resource is seekinggetDuration()Returns a double value for the length of a truyền thông resource in secondsgetPosition()Returns a long value of the current playback position in secondsPlayer events

    The player emits specific events about changes in its state. For specific player events, you can add sự kiện listeners. For certain events, its possible to access the corresponding player property value using thepayloadmethod.

    EventInfoPayload methodApiReadyEventSent when the player is ready to accept API commands. Do not try to call functions before receiving this eventStartEventSent the first time the player attempts to start the playbackVideoChangeEventSent when a new video has been loaded in the playergetPayload()returns video id & video titleLoadedMetaDataEventSent when the videos metadata is loadedAdStartEventSent when the player starts to play an ad truyền thông resourceAdTimeUpdateEventSent when the playback position of an ad changesAdPlayEventSent when the player starts the playback of an adAdPauseEventSent when the player pauses an ad resourceAdEndEventSent when the player reaches the end of an ad truyền thông resourceVideoStartEventSent when the player starts to play the truyền thông resourceTimeUpdateEventSent when the playback position changesSeekingEventSent when the player is starting to seek to another position in the videogetPayLoad()will return the position at which the seek method was triggeredSeekedEventSent when the player has completed a seeking operationgetPayLoad()will return the position at which the seek method seeks toProgressEventSent when the browser is fetching the truyền thông dataDurationChangeEventSent when the duration property of the video becomes available or changes after a new video loadgetPayload()returns the duration property of the videoPlayingEventSent when the content truyền thông resource playback has startedPauseEventSent when the content truyền thông resource playback has pausedVideoEndEventSent when the player reaches the end of the content truyền thông resourcePlaybackReadyEventSent when playback starts after the play method returnsQualitiesAvailableEventSent when qualities are availablegetPayload()returns qualities which are availableQualityChangeEventSent when the video quality changesgetPayload()returns the quality valueVolumeChangeEventSent when the volume or mute state changesgetPayload()returns volume state and muted stateFullScreenToggleRequestedEventSent when the fullscreen toggle button is requestedControlChangeEventSent when the UI controls appear or disappeargetPayload()returns if player UI controls are visible

    Below is an example of adding listeners for multiple events, it is then possible to use the sự kiện payload method to get the corresponding events property value.

    dailyMotionVideoPlayer.setEventListener sự kiện ->
    when (sự kiện)
    is ApiReadyEvent -> …
    is StartEvent -> …
    is LoadedMetaDataEvent -> …
    is ProgressEvent -> …
    is DurationChangeEvent -> …
    /* And many more sự kiện */
    else ->
    /* In case a POJO is not available you can directly access the raw data */
    if (sự kiện.name == “_generic_”)
    /* Do some stuff for my sự kiện: parse the raw date to extract the sự kiện name or values */
    Log.d(“Event with payload: $sự kiện.payload”)

    Player Ready Event:
    When using the Player with any of our of SDKs, we recommend before you make any API commands, wait till after the API ready sự kiện is sent by the player. You can pick this up in your android app using theApiReadyEvent.

    Preload player:
    Its possible to load the player and the video separately. In your application, you can preload the player before the user attempts to play a video. In order to preload the player without a video being displayed. Use theinitialize()method and base the baseUrl of just the player with a video not defined,dailymotion/embed/.

    Reuse player:
    When utilizing the player via our SDKs in an application, you can reuse the same player instance. Use theload()method passing in the video id after initializing the player.

    Handle full-screen orientation:
    Any activity you are using your player in, you should add the below snippet in your AndroidManifest.XML . ThesetFullScreenButton()method which is available, doesnt have complete control of the full-screen functionality in your application. This should be used in parallel with your own native application functionality adjusting the player to take the whole screen space. This method controls the UI fullscreen component and updates the player state.

    android:configChanges=”orientation|screenSize”

    Google player services:
    The SDK uses Google Play Services to get the Advertising Id, you may want to override the play-services-ads version to avoid conflicting with other play services artifacts.

    dependencies
    implementation “com.google.android.gms:play-services-ads:[your_play_services_version]”

    Picture In Picture:
    Our flagship Dailymotion app use our Android SDK, although we cant provide out of the box PiP functionality, it is possible to achieve this like we have done, depending on your software architecture. You can review info on Googles android Picture-in-Picture supporthere.

    TCF2

    Our Android SDK complies with IAB TCF2 standards so its easy to access the stored content string and pass it to the Player.

    Using a recognized CMP, generate the consent string and store it in the correct location as specified by the TCF2 iAB specification. After generating the content string then pass it to the Player using thetcf2Handler.loadConsentString(content = this)method.

    OM SDK

    Open Measurement SDK from IAB is designed to facilitate third party viewability and verification measurement for ads served to web video and mobile app environments. For more details seehere.

    We have integrated the SDK in our Dailymotion Player SDK and it does more or less everything out of the box :

    • Ad session management
    • Ad main signals (play, buffer_start, buffer_end, pause, resume, quartiles, click)
    • Device and Player volume management
    • Basic Player state handling. NORMAL or FULLSCREEN based on player fullscreen state.

    Please note that it is recommended to update at all times the player state if your app has more player layout variety, such as mini-player, picture-in-picture, etc. This can be achieved by updating the OMHelperplayerState field:

    OMHelper.playerState = PlayerState.COLLAPSED

    EnumDescriptionMINIMIZEDThe player is collapsed in such a way that the video is hidden. The video may or may not still be progressing in this state, and sound may be audible. This refers to specifically to the video player state on the page, and not the state of the browser windowCOLLAPSEDThe player has been reduced from its original size. The video is still potentially visibleNORMALThe players default playback sizeEXPANDEDThe player has expanded from its original sizeFULLSCREENThe player has entered fullscreen mode

    The Dailymotion Swift iOS SDK is aswiftwrapper around theWKWebViewClass that allows developers to easily embed the Dailymotion Player in their app and let them communicate with its API natively.

    The Swift iOS SDK is open source and you can get all required information plus a sample app here on ourGitHub. It requires Xcode 8 and later, Swift 4 and iOS 8+. If you require an Objective-C version please check out our githere.

    The Dailymotion iOS SDK, starting from version 3.10.0 has integrated the latest changes on the IDFA collection as part of the App Tracking Transparency compliance. It is recommended to all partners to utilize the latest SDK version, IDFA will not be collected on versions prior to 3.10.0 on iOS 14.5.

    How to use:

  • Add our SDK to your project, the easiest way to do so is with CocoaPods, a dependency manager solution. Add the below pod to your Podfile.use_frameworks! pod ‘DailymotionPlayerSDK’
  • ImportDailymotionPlayerSDKinto each file where you need to create an instance of Dailymotion player.import DailymotionPlayerSDK
  • Inside a view controller where you want to display the player, create a freshDMPlayerViewControllerinstance and set your view controller asdelegate. Please, ensure your view controller conforms to theDMPlayerViewControllerDelegateprotocol.
  • import DailymotionPlayerSDK
    class VideoViewController: UIViewController
    private lazy var playerViewController: DMPlayerViewController =
    let controller = DMPlayerViewController(parameters: [:])
    controller.delegate = self
    return controller
    ()

    //MARK: – Conform to protocol
    extension VideoViewController: DMPlayerViewControllerDelegate
    func player(_ player: DMPlayerViewController, didReceiveEvent sự kiện: PlayerEvent)

    func player(_ player: DMPlayerViewController, openUrl url: URL)

    func playerDidInitialize(_ player: DMPlayerViewController)

    func player(_ player: DMPlayerViewController, didFailToInitializeWithError error: Error)

  • Add theplayerViewControlleras a child view controller. Then pass a video id to the playerload()method. Once the player is initialized, it will take care of loading the video and start the playback.playerViewController.load(videoId: “x84sh87”)
  • To customize the player, select the required parameters from the playerparameter listand pass them to the player init method. The params value should contain a String Array with the customization values. If you dont need any customization, pass an empty array.

    let parameters: [String: Any] = [
    “logo”: “false”, //to disable the Dailymotion logo
    “ui-highlight”: “FF0000”, //to color the player UI using HEX value
    ]
    let playerViewController = DMPlayerViewController(parameters: parameters)

    Some parameters can be passed in on player creation but also used with theloadmethod to update their runtime config. These parameters includevideo,playlist,ads_params&start. These params require some encoding on the partners side. Please see the example below of the steps required.

    func loadVideo(withId id: String)
    let parameters = [“start”: 30]
    guard
    let encoded = try? JSONEncoder().encode(parameters),
    let params = String(data: encoded, encoding: .utf8)
    else return
    playerViewController.load(videoId: id, params: params)

    Player Parameters for iOS

    Use the below parameters to customize your player via the iframe or SDK embed.

    ParameterInfoTypeautoplayAutomatically attempt to start playback with sound, if it is blocked by the browser, the player will force the video muteBooleancontrolsWhether to display the player controls, true by defaultBooleanidID of the player unique to the page to be passed back with all API messagesStringmuteWhether to mute the videoBooleanqualitySpecify the suggested playback quality for the videoNumbersharing-enableWhether to display the sharing buttonBooleanstartSpecify the time (in seconds) from which the video should start playingNumbersubtitles-defaultSpecify the default selected subtitles languageStringsyndicationPass your syndication key to the playerStringui-highlightChange the default highlight color used in the controls (hex value without the leading #). Color set in the Partner HQ will override this paramStringui-logoWhether to display the Dailymotion logoBooleanui-start-screen-infoWhether to show video information (title and owner) on the start screenBooleanplaylistSpecify a playlist ID to populate the Up Next Queue with videos from a playlistStringfullscreenWhether to display the fullscreen buttonBooleanscaleModeSpecify the default focus of the player in order to reframe and refocus on a specific area in the video. To be used for scaling and repurposing of videos between different aspect ratios for example landscape to portrait. Values ( fit, fill, fillLeft, fillRight, fillTop, fillBottom )StringloopWhether to loop a video or an entire playlist. A video embed will start over again automatically. A playlist embed will start to play from the first item in the playlist after the entire playlist has finishedBooleanMethods

    Our iOS SDK is loaded with all the functionality you need to create a unique video-centric application. Once the player is loaded, you can use the Player API and our player methods.

    playerViewController.play()

    MethodDescriptionload(params: String)Calls the initialize method, loads the player with a video associated with the video id (e.g. x7tgad0).play()Starts or resumes video playbackpause()Pauses videos playbacktoggleFullscreen()Toggle the fullscreen state of the player and fullscreen UI component. The method should be used in association with the native fullscreen functionality in your app.unmute()Unmute the playermute()Mute the playerseek()Seek to the specified time in video playback in seconds.toggleControls()Disables the player UI when set to false, enables when true

    The player sends events when a specific player property changes or becomes available. It is possible to add listeners to specific events. The events are split between two groups:namedEventandtimeEvent. For a list of all events, please see our Player API referencehere.

    Below is an example of how to set a listener forloadedmetadata&apireadyevent.

    extension ViewController: DMPlayerViewControllerDelegate
    func player(_ player: DMPlayerViewController, didReceiveEvent sự kiện: PlayerEvent)
    switch sự kiện
    case .namedEvent(let name, _) where name == “loadedmetadata”:
    print(“Player Metadata loaded”)
    case .namedEvent(let name, _) where name == “apiready”:
    print(“Player is ready”)
    default:
    break

    It is possible to get access to information about the players current state or specific player properties. Add a listener to an sự kiện and retrieve the corresponding player property, depending on the sự kiện type, use the data or position value.

    func player(_ player: DMPlayerViewController, didReceiveEvent sự kiện: PlayerEvent)
    switch sự kiện
    case .namedEvent(let name, let data):
    print(“(name) – (data)”)
    case .timeEvent(let name, let position):
    print(“(name) – (position)”)

    Player Ready Event:
    When the player is ready to receive API commands it will send theapireadyevent. Listen to this sự kiện to ensure the player is ready to receive any API commands.

    Preload player:
    In your application, you can preload the player before the user attempts to play a video. In order to load the player, you must use theDMPlayerViewController()method, followed by the load method when you want to load a video in the player.

    Reuse player:
    When using our player in an application, you can (and should) reuse the same player instance, therefore a single-player instance can load multiple videos.

    Handle fullscreen orientation and state:
    ThetoggleFullscreen()method toggles the fullscreen UI component and the player fullscreen state, it doesnt have control of the fullscreen functionality of your application. This method should be used alongside the native functionality adjusting the player orientation. You can see an example of how it could be handled in our sample application.

    Sample application:
    You can access a sample application utilizing our SDK from our githere. Check out the SDK repo and the sample will be available.

    TCF2

    The iOS SDK complies with IAB TCF2 standards and will take care of everything by default starting from version3.8.0+. It will automatically access the stored content string and pass it through to the player.

    OM SDK

    Open Measurement SDK from IAB is designed to facilitate third-party viewability and verification measurement for ads served to web video and mobile app environments. For more details seehere.

    We have integrated the SDK in our Dailymotion Player SDK and it does more or less everything out of the box:

    • Ad session management
    • Ad main signals (play, buffer_start, buffer_end, pause, resume, quartiles, click)
    • Device and Player volume management
    • Basic Player state handling. NORMAL or FULLSCREEN based on player fullscreen state.

    Please note that It is recommended to update at all times the player state if your app has more player layout variety, such as mini-player, picture-in-picture, etc. This can be achieved by updating theplayerStateproperty in your DMPlayerViewController instance.

    player.playerState = .fullscreen

    Player state

    EnumDescriptionMINIMIZEDThe player is collapsed in such a way that the video is hidden. The video may or may not still be progressing in this state, and sound may be audible. This refers to specifically to the video player state on the page, and not the state of the browser windowCOLLAPSEDThe player has been reduced from its original size. The video is still potentially visibleNORMALThe players default playback sizeEXPANDEDThe player has expanded from its original sizeFULLSCREENThe player has entered fullscreen mode

    Embed the player on AMP

    AMP (Accelerated Mobile Pages) is an open-source project which provides a robust framework for creating a lightweight experience of a webpage that loads lightning fast on mobile connections.

    In order to build these pages the framework provides a large library of components. This library includes a dedicated Dailymotion AMP component which is available for anyone to use Dailymotion videos on their AMP site.

    Required Script

    Our Component

    Example embed

    In order to autoplay correctly on AMP pages, it is required that both autoplay and mute are configured. Add both theautoplay&data-mute=”true”to configure this. Our tap to unmute feature wont be visible, however, this framework provides its own version.

    For player parameters that dont have matching AMP attributes, its possible to add in any player parameter using the data-params-Player_Param.

    Please note that our player is compliant with the TCF API within the AMP framework also. The amp-content component needs to be added and configured to facilitate the ability to collect and store a users consent. This can easily be managed by adding the configuration below.

    Furthermore, we recommend blocking the amp-dailymotion component until the user accepts consent. This can easily be achieved by adding data-block-on-consent into the player amp embed. For more info on the consent component see here.

    “exposesTcfApi”: true

    oEmbed is a format for allowing an embedded representation of a URL on third-party sites. The protocol allows a website to turn a Dailymotion video page URL into a structured data set, making it easy to embed and share content across the web.

    When to use it:

    This protocol is the preferred method when you need to transform the URL provided into an embed code. For more information, see theoEmbed specification.

    How to use it:

    Use the following endpoint to request the corresponding video information using only a Dailymotion video URL. Add in URL params from the table below to configure the response.

    dailymotion/services/oembed?url=VIDEO_URL?PARAM1&PARAM2

    Example call using URL parameters:

    dailymotion/services/oembed?url=dailymotion/video/x7tgad0?maxwidth=480&maxheight=269&autoplay=true

    Example JSON response:

    Iceland”,
    “description”: “”,
    “author_name”: “Dailymotion player demo”,
    “author_url”: “dailymotion/dailymotionplayerdemo2”,
    “width”: 478,
    “height”: 268,
    “html”: “”,
    “thumbnail_url”: “s2.dmcdn/v/SBL5q1U_Klu8xz_7m/x240”,
    “thumbnail_width”: 427,
    “thumbnail_height”: 240

    Available URL parameters

    ParameterParameter descriptionurlThe Dailymotion URL for a video (required)maxwidthThe maximum width the embedded video can take on the destination pagemaxheightThe maximum height the embedded video can take on the destination pageformatResponse format, eitherjsonorxml. Defaults tojsoncallbackWhen returning JSON, wrap in this functionautoplayAutomatically start playback of the video. Defaults tofalsesyndicationYour syndication key

    Customize the player

    The Dailymotion Player can be customized to match your brand perfectly, with a modern UI that works across all platforms. If you want to develop a custom experience our SDKs give full control of the Player via the Player API.

    Depending on where and how you embed the player, how the player is customized will vary.

    On web

    The main Player experience must be created and managed through the Player configurator UI in the Partner Space (Players tab) or the REST API, these allow you to configure theplayer settingsseen from the listhere. Additional customization is achievable at runtime usingplayer parametersseen from the listhere

    In-app

    The Player in-app using our native SDKs can be customized using client-side parameters. The parameters which are available in these environments can be found in their correspondingiOS parametersandAndroid parameterssections.

    Working with player settings

    When embedding the Player on the web its required to create a Player configuration that specifies the Player settings and behavior.

    The Player settings manage the main player experience and are controlled through the Player configurator UI in the Partner Space (Players tab) or using theREST API.

    Player settingFieldDefaultDescriptionValuesAutostartautostartfirstTimeViewableTo control the players autoplaying behaviour”firstTimeViewable”,”on”,”off”Picture-in-PicturepipoffTo specify the Dailymotion picture-in-picture behaviour”instant”,”on”,”off”Start PiP in Expandedenable_start_pip_in_expandedfalseWhether to start the PiP in expanded mode on small viewports”true”,”false”Aspect ratioaspect_ratio16:9To control the aspect ratio of the player. Only available when embedding using JavaScript”16:9″,”4:3″,”1:1″,”3:4″,”9:16″,”inherit”ColorcolorundefinedChange the default highlight color used in the controls (hex value without the leading#). Color set in the Partner HQ will override this paramControlsenable_controlstrueWhether to enable the player controls or not”true”,”false”Logoenable_dm_logotrueWhether to display the Dailymotion logo or not”true”,”false”Queueenable_queuetrueWhether to show the Up Next queue. see note below”true”,”false”Auto Nextenable_autonexttrueWhether to play automatically the next item in the queue”true”,”false”Sharingenable_sharingtrueWhether to enable the sharing button or not”true”,”false”Video Infoenable_infotrueTo remove title and video owner information”true”,”false’Channel Owner Linkenable_channel_linktrueTo remove the link on the channel”true”,”false”Video Title Linkenable_video_title_linktrueTo remove the link on the video title”true”,”false”Embed script URLembed_script_urlundefinedURL of the player to be used in a script HTML tagLibrary script URLlib_script_urlundefinedURL of the player embed library to be used in a script HTML tagEmbed HTML URLembed_html_urlundefinedURL of the player to be used in an iFrame HTML tagSharing URLenable_sharing_url_locationpage linkTo control whether the user shares the page link or the dailymotion link location when using the share functionality of the player. The page link is only available when embedding using JavaScript

    Working with player parameters

    Additional runtime customization is achievable when embedding the Player on the web using client-side parameters from the table below. These parameters allow you to specify additional Player behavior or pass in required values to a specific Player embed. Note that the main Player experience is controlled using Player Settings managed in the Partner Space (Players tab) or REST API.

    These URL encoded query strings can easily be added to thedata-paramsattribute on the Player embed script, within thecreatePlayer()method when using the Player API or passed into thesrcURL for an Iframe embed.

    NameParameterDefaultDescriptionValuesTypeVideo IDvideoundefinedThe ID of the video to loadStringPlaylist IDplaylistundefinedThe ID of the playlist to loadStringAdvertising ConfigcustomConfigundefinedFor passing in unique keys for advertising purposes. For example,customConfig[customParams]=adKeyObjectSyndicationsyndicationKeyundefinedTo pass in a syndication key to the playerStringScale modescaleModefitTo adjust the players video focus”fit”,”fill”,”fillLeft”,”fillRight”,”fillTop”&”fillBottom”EnumMutemutefalseWhether to mute the video or not. To note, enabling mute may impact monetization. The Player provides smart mute behavior, it tries to automatically start the video playback with sound. If this isnt possible due to browser prevention, there is a fallback mechanism and the Player reattempts to play the video but with the sound set to mute.”true”,”false”BooleanStartstartTime0Specify the time (in seconds) from which the video should start playingNumberLooploopfalseTo set the video to loop”true”,”false”Boolean

    Player embed script

    Add theURL encodedquery string to thedata-paramsattribute with the Player embed script.

    Player library script

    Add theURL encodedquery string to the params object within thecreatePlayer()method when creating the Player with the Player Library and Player API.

    dailymotion
    .createPlayer(“my-dailymotion-player”,
    video: “x84sh87”,
    playlist: “x5zhzj”,
    params:
    startTime: 15,
    loop: true,
    mute: true,
    ,
    )
    .then((player) => console.log(player))
    .catch((e) => console.error(e));

    iFrame embed

    Add theURL encodedquery string after the video ID in the src attribute of the iFrame.

    

    The Dailymotion Player is compatible with native Picture-in-Picture(PiP) in addition to our own out-of-the-box Picture-in-Picture product. Our PiP solution is easily managed through the Partner HQ, it delivers a smooth and engaging user experience and will help boost your monetization opportunities.

    A verified partner can enable the Dailymotion Picture-in-Picture feature in the Player settings using the Partner HQ or REST API. This functionality requires JavaScript and only be used with the Player Embed Script or Player Library Script.

    PiP settings

    As the user scrolls the page, the video must transition from playing in the in-page video player to playing in a sticky video player, which remains in view as the user scrolls the page.

    ValueInfopip: offThe PiP is not enabledpip: onThe PiP will tranisition after the main player was firstly seen by the user and after they scroll the page so less than 50% of the main player is within the viewportpip: instantThe PiP will launch once the player is loaded and the main player isnt in the users viewport

    When triggered a mini player will be displayed at the bottom right on wide screens and at the top on narrow screens. Further positioning can be achieved using custom CSS, see the section below.

    Desktop-specific behavior

    The PiP frame will transition and appear at the bottom right of the screen. Its optimized for viewability, performance, monetization and built with a minimal, user-centric design. The desktop PiP will have a minimum size of 410px width with a 16:9 aspect ratio sized responsively.

    Mobile-specific behavior

    The PiP frame on mobile, or on a narrow viewport, the player will automatically adapt and have two modes:

    ValueInfocollapsedThe video player height is reduced not to interfere with page content (articles, text, images)expandedThe video player is at full width and height (preserving video ratio)

    By default, the player will initially transition to a collapsed format unless the configuration is set to to Start PiP in expanded option in the partner HQ or REST API. The viewers can alter between the mobile PiP formats using the collapsed toggle on the UI. During advertisements the PiP will automatically expand to preserve ad viewability. The mobile PiP format will take 100% of the width on a mobile screen.

    PiP customization

    The PiP will be displayed at the bottom right on wide screens and at the top on narrow screens by default. Its possible to reposition the PiP by adding specific CSS code for the dedicated element IDs. You can view the CSS samples below or view a live demo in our codepen.io collectionhere.

    CSS SelectorInfo#dailymotion-pip-large-viewportTargets PiP for corner display on large viewports#dailymotion-pip-small-viewportTargets PiP for top sticky display on small viewports

    Example: PIP desktop top right:

    #dailymotion-pip-large-viewport
    right: 0 ;
    top: 0 ;

    

    Example: PIP desktop bottom left without margin:

    #dailymotion-pip-large-viewport
    bottom: 0 ;
    margin: 0 ;
    left: 0 ;

    

    Example: Reposition PIP mobile below menu bar:

    #dailymotion-pip-small-viewport
    top: 50px ;

    

    Reposition PIP mobile bottom of the page:

    #dailymotion-pip-small-viewport
    top: 50px ;

    

    Programmatically interacting with PiP

    The PiP can be programmatically closed, resumed, collapsed or expanded using allocated methods via the Player API. The PiP setting has to be enabled in the player configuration. Once the PiP is activated the Player API exposes four global methods:

    TypeMethodInfoClose PiPdailymotion.pipClose()To suspend PiP functionality.Resume PiPdailymotion.pipResume()To resume PiP functionality after it has been suspended.Collapse mobile PiPdailymotion.pipCollapse()To collapse the sticky PiP displayed on mobile (delayed if an ad is running).Expand mobile PiPdailymotion.pipExpand()To expand the sticky PiP displayed on mobile.

    Working with autostart

    In recent years browsers have been setting stricter autostart policies. Although you can activate the autostart behavior in the players configuration, complete control over autostart behavior isnt possible, due to users browser settings.

    Our player includes smart autostart behavior that is engineered to maximize the chances of automatically playing a video in all browser conditions. When autostart is enabled, the player goes through the following waterfall:

  • If the browser allows autostarting, the player will automatically play with sound.
  • If autostart is prevented by the browser, it will attempt to play the video again but will automatically mute itself. In this case on mobile devices, the player will display aTap to unmutecall to action that allows users to unmute with a single tap anywhere on the player.
  • If the browser doesnt allow autostart the player will display a start screen and wait for the users interaction to start video playback.
  • The advertising parameter is a custom parameter used for targeting and reporting purposes. Verified partners can use the parameter to dynamically pass information to their VAST tag. The parameter is passed in on player initialization and can be updated dynamically by the Player API.

    Depending on the embed type some encoding may be required if utilizing multiple ads parameters values.

    Some configuration is also required on our side. If more complex use-cases need to be handled we invite you to contact our Ads Ops team. Please see examples of the below embed types on how to pass in the parameter on initialization.

    Example with the Player Embed Script

    Pass values through using thecustomConfig[customParams]parameter in thedata-paramsattribute in thescripttag. Example values: [test/value=1234&value2=3214]

    Pass values through when creating the player usingthe createPlayer()method. Example values[test/value=1234&value2=3214]

    dailymotion.createPlayer(“player1”,
    video: “x84sh87”,
    params:
    customConfig:
    customParams: “test/value=1234&value2=3214”,
    ,
    ,
    );
    

    Using the methodsetCustomConfig()in order to dynamically update the advertising parameter value, a new value will be sent which then gets updated when the player loads the next video file.

    dailymotion.getPlayer(“player”).then((player) =>
    player.setCustomConfig( customParams: new_params )
    );
    

    Pass value through using the Player query string parameter customConfig[customParams]. Example values:[test/value=1234&value2=3214]

    

    It may be required to adjust the referrer-policy string to match your own privacy policy or integration requirements. The Dailymotion video player relies on the referrer passing the full URL to provide valuable products to publishers. Our player by default wont specify the referrer-policy setting, if no referrer-policy is set the browsers default policy will be applied.

    You have full control over how much data is available in the referrer. If you want the Dailymotion video player to receive the full URL in the Referer HTTP Header you need to add the no-referrer-when-downgrade to the referrer-policy parameter in the player embed. Please see the embed examples below on how to adjust the policy when using web embeds.

    Player script embed

    dailymotion.createPlayer(“player”,
    video: “x84sh87”,
    referrerPolicy: “no-referrer-when-downgrade”,
    );

    

    To create a player through the Dailymotion REST API you need to have themanage_playersspecific permissions. Please refer to the list ofextended permissionsto obtain them. Define and specify the required fields and then perform aPOSTrequest. For the exhaustive list of fields refer tothis page.

    Example of player creation:

    curl -H ‘Authorization: Bearer ‘
    -d ‘label=My new player’
    api.dailymotion/me/players
    

    Once a player has been created and associated with your account it is then possible to update it or delete it. You can test and learn more about the REST API with theexplorer.

    After the creation of your player, you must add it to your page using a generatedscript embed or iFrame. You can retrieve the script URL from the REST API (seeembed_script_urlfield).

    Working with TCF2

    The embedded Dailymotion Player complies with the IAB TCF 2 standards and automatically detects any TCF 2-certified CMP. In such a case, it collects consent sent by a Publishers TCF 2.-certified CMP and does not deploy its independent built-in consent dialogue (i.e. a cookie banner). Note that Dailymotion is a registered IAB Vendor (n° 573).When available, the Dailymotion Player will always rely on the consent that it receives from a CMP through the standard CMP integration.The CMP integration is currently offered at no additional fees to Publishers.

    Having a single cookie banner contributes to a less disruptive user experience which may improve the consent rate and potentially result in increased revenues. If the embedding website doesnt use a TCF 2-compliant CMP, we use the Players built-in cookie banner as a fallback solution.

    JavaScript Player API Reference

    Each script used to embed the player also provides access to the Player API without any additional configuration, everything is available and bundled from the Player embed script. The Player API allows you to create a player, retrieve information about a specific player state, listen to player events and trigger player methods.

    The player is loaded asynchronously using aPromise, which on resolve returns a player object. In order to get access to a player, you can retrieve a player using one of the below methods.

    Methods

    API commands can be called to programmatically create and control the player.

    Global methods:

    MethodInfodailymotion.createPlayer(‘source_id’, video:String, playlist:String, player:String, params:Object, referrerPolicy:String)On resolve thePromisewill return a created player at the position of thesource_idon the page. Avideo,playlistorplayercan by specified using their corresponding paramater and unique id. If you already have multiple player configurations embedded in your page, you must specify theplayerconfiguration to use, otherwise the default one will apply, seemultiple player configurations. For additional customization you can add runtimeparamsto the player, seePlayer parametersdailymotion.getPlayer()On resolve thePromisewill return a player, if there is a single player instance, otherwise it will be rejected if there are multiple player embedsdailymotion.getPlayer(‘source_id’)On resolve thePromisewill return the specified player, pass the container ID of the specific player as an argument into thegetPlayer()methoddailymotion.getAllPlayers()Returns an array ofPromises. EachPromisereturns one of the player of the pagedailymotion.pipClose()To deactivate PiP, the method applies to the whole webpagedailymotion.pipResume()To resume PiP, the method applies to the whole webpage.dailymotion.pipCollapse()To collapse the mobile sticky PiP, the method applies to the whole webpagedailymotion.pipExpand()To expand the mobile sticky PiP, the method applies to the whole webpage

    Player methods:

    Once youve access to a player on the page, you can then control that player programmatically.

    MethodInfoValuesTypesloadContent()To load a video or a video with a playlist, a video id is mandatory(video:String, playlist:String, startTime:Number)Objectplay()To start or resume video playbackpause()To pause video playbacksetVolume()To set the players volume to the specified levelBetween0&1FloatsetSubtitles()To activate a subtitles track to a specified language if availableStringsetQuality()To set the videos quality to the specified quality[240,380,480,720,1080,1440,2160default]Stringseek()To seek to the specified time in video playback in secondsNumbersetControls()To enable or disable the players controls UI, we advise disabling controls on intialization using the player configurator if utilizing your own player UI design”true”,”false”BooleansetFullscreen()To enable or disable fullscreen mode”true”,”false”BooleansetMute()To set the mute mode of the player”true”,”false”BooleansetCustomConfig()To set the config for ads, dynamically update the advertising parameter value, use the method to send a new value which then gets updated when the player loads the next video fileObjectsetScaleMode()To adjust the player view of the video screen”fit”,”fill”,”fillLeft”,”fillRight”,”fillTop”&”fillBottom”EnumupdateParams()To change the following player config values at runtimescaleMode,mute,volume,enableControls&customConfigObjectdestroy()To destroy a player instance pass in specified player idon()To set up alistenerfunction returning the player state that will be called whenever the specifiedeventis dispatched by a player instance. An optional object can be passed as a 3rd parameter. The only available option is currentlyonce, and expects aBooleanvalue indicating that the listener should be invoked at most once after being added. Iftrue, the listener would be automatically removed when invoked(sự kiện:String, listener:Function, [once:Boolean])off()To remove a previously registered eventlistenerfrom a player instance. If thelisteneris not specified, it will remove any existing listeners associated with the sự kiện(sự kiện:String, [listener:Function])getState()To retrieve the current state of the player. See usage in Player API State sectionheregetSettings()To retrieve the Partner Space configuration of a player. See usage in Player API State sectionhere

    Events

    The player emits events relating to the change of the player state, video playback and ad content. To pick up on these events use the method player.on()

    player.on(“YOUR_EVENT”, (state)).

    It is also possible to unbind specified listeners using an additional method player.off()

    player.off(“YOUR_EVENT”).

    Player events EventInfoPLAYER_ASPECTRATIOCHANGESent when the aspect ratio of the player changes after callingsetAspectRatio(‘4:3’))PLAYER_CONTROLSCHANGESent when the availability to use our player controls changesPLAYER_CRITICALPATHREADYSent every time a video is ready to play, or started playing (depending on autoplay settings, and their resolution by the browser), or is unable to play (blocked, restricted, unavailable). Listen to this sự kiện if you want to defer doing network-heavy and JavaScript-heavy work, to allow the optimal delivery of the first frames of the video to the usePLAYER_ENDSent when the playback of the content video, and eventual post-roll ad video is completedPLAYER_ERRORSent when the player triggers an error. Error code available in the Player State objectPLAYER_PIPEXPANDEDCHANGESent when the Picture-in-Picture expanded mode changes, only on small viewportsPLAYER_PLAYBACKPERMISSIONSent each time any playback request has failed or if the initial playback attempt has succeededPLAYER_PRESENTATIONMODECHANGESent when the player transitions to or from a Picture-in-Picture state, either native or the dailymotion version, or when the player enters or exits the fullscreen statePLAYER_SCALEMODECHANGESent when the scale mode of the player changes after usingsetScaleMode()PLAYER_STARTSent the first time the player attempts to start the playback, either because of user interaction, an autoplay parameter or an API call (e.gplay(),loadContent(), etc.)PLAYER_VIDEOCHANGESent when a new video has been loaded in the player. (e.g. after callingloadContent( video: ‘xID’ ), or at player start-up)PLAYER_VIEWABILITYCHANGESent when the player viewability values changes (50% of the player is within the users viewport)PLAYER_VOLUMECHANGESent when the volume level or mute state changesPLAYER_HEAVYADSINTERVENTIONSent when the player is unloaded from the page due to Chrome browsers heavy ads intervention policiesVideo Events Video EventInfoVIDEO_BUFFERINGSent when the player has to temporarily stop video playback for further buffering of contentVIDEO_DURATIONCHANGESent when the duration property of the video becomes available or changes after a new video loadVIDEO_ENDSent when the player completes playback of the content videoVIDEO_PAUSESent when the video playback has pausedVIDEO_PLAYSent when the playback state of the content video is no longer paused, as a result of the play method or the autoplay attributeVIDEO_PLAYINGSent when the content video starts playing, after the play or waiting eventVIDEO_PROGRESSSent when the browser is fetching the truyền thông dataVIDEO_QUALITIESREADYSent when video qualities are availableVIDEO_QUALITYCHANGESent when the video quality changesVIDEO_SEEKENDSent when the player has completed a seeking operationVIDEO_SEEKSTARTSent when the player starts to seek to another position in the video timelineVIDEO_SUBTITLESCHANGESent when the current subtitle changesVIDEO_SUBTITLESREADYSent when subtitles are availableVIDEO_STARTSent when the player begins playback of the content videoVIDEO_TIMECHANGESent when the playback position changesAd Events Ad EventInfoAD_COMPANIONSREADYSent when a companion ad is received. Companion ads should be played in sync with the main ad (linear/non-linear) by listening to eventsAD_STARTandAD_ENDAD_DURATIONCHANGESent when the duration property of the video advertisement becomes available or changes after a new video loadAD_ENDSent when the player completes playback of an adAD_IMPRESSIONSent when the first ad frame is displayedAD_LOADEDSent when the player has loaded and buffered the creatives truyền thông and assets either fully or to the extent that it is ready to play the mediaAD_PAUSESent when the player pauses an adAD_PLAYSent when the ad playback starts or continues after being in a paused stateAD_STARTSent when the player begins playback of an ad videoAD_TIMECHANGESent when the playback position of an ad changesAD_CLICKSent when a user clicks on a video ad

    Example of adding a listener to the player sự kiện [PLAYER_START]

    player.on(dailymotion.events.PLAYER_START, (state) =>
    console.log(“Received PLAYER_START sự kiện. Current state is:”, state);
    );
    

    Example of adding a unique listener

    If you want a listener to be invoked only once, pass an additional object composed ofonce:trueinto the method.

    player.on(
    dailymotion.events.PLAYER_START,
    (state) =>
    console.log(“Received PLAYER_START sự kiện. Current state is:”, state);
    ,
    once: true
    );

    To access data use thegetState()method, on resolve, it will return an object representation of the player state.

    From the state, it is possible to access required player, video or advertising data for your video application or analytics purposes. You can determine for example, if the PiP is currently displayed, the duration of the video or if the player is in or out of the users viewport.

    NameTypeInfoValuesadAdvertiserNameStringThe advertiser name ornulladCompanionArrayAn array of parsed companion ad creativesadCreativeAdIdStringThe universal ad id node from the VAST or the ad id of the creative node from the VASTadCreativeIdStringThe id of the creative node from the VASTadDescriptionStringThe description of the ad ornulladDurationNumberThe duration time of the ad resource in secondsadEndedReasonStringThe reason why the last ad ended”error”,”stopped”,”skipped”ornulladErrorObjectContains the infos about the last error that occurred with the ad ornulladIdStringThe id of the adadIsPlayingBooleanIf an ad resource is running”true”,”false”adIsSkippableBooleanIf the ad can be skipped by the user at this moment”true”,”false”adPositionStringThe position of the ad in the video,nullif no ad is running”preroll”,”midroll”,”postroll”or”null”adSkipOffsetNumberThe remaining time before the ad can be skipped or -1 if no ad is runningadTimeNumberThe current playback position of an ad in secondsadTitleStringThe title of the ad ornullplayerAreControlsEnabledBooleanIf the player controls are enabled”true”,”false”playerAspectRatioStringThe player current aspect ratio”inherit”,”16:9″,”4:3″,”1:1″,”3:4″,”9:16″playerErrorObjectContains information about the last error that occurred in the player, includingtitle,messageandcodeplayerIsAlertDialogDisplayedBooleanIf the player has the alert dialog displayed”true”,”false”playerIsBufferingBooleanIf the player is loading the truyền thông resource”true”,”false”playerIsCriticalPathReadyBooleanIf the player is ready to play”true”,”false”playerIsMutedBooleanIf the player is muted”true”,”false”playerIsNavigationEnabledBooleanIf the next and previous controls in the PiP are enabled”true”,”false”playerIsPipNativeSupportedBooleanIf the player does tư vấn the native PiP”true”,”false”playerIsPlaybackAllowedBooleanIf the player is allowed to play, depending on the browser permissions”true”,”false”playerIsPlayingBooleanIf the player is currently playing video or ad content”true”,”false”playerIsStartScreenBooleanIf the player is in start screen”true”,”false”playerIsReplayScreenBooleanIf the player is in replay screen”true”,”false”playerIsViewableBooleanIf the player is within the viewability threshold”true”,”false”playerNextVideoStringThe id of the video next video in the queueplayerPipDisplayStringThe current display mode of PiP, If its display on a larger/smaller Screen”largeViewport”,”smallViewport”playerPipStatusStringThe current PiP feature status”enabled”,”disabled”or”closed”playerPipIsExpandedBooleanIf the mobile sticky PiP is expanded”true”,”false”playerPlaybackPermissionReasonStringThe reason why the playback has been allowed or not”allowedFallbackMuted”,”allowed”,”rejectedInactiveTab”,”rejectedByBrowser”playerPresentationModeStringThe current mode where the player is displayed”inline”,”nativePip”,”pip”or”fullscreen”playerPrevVideoStringThe id of the video previous video which was playedplayerScaleModeStringThe players current scale mode”fit”,”fill”,”fillLeft”,”fillRight”,”fillTop”,”fillBottom”playerVolumeNumberThe current volume level. The volume and mute params operate separately, therefore, you could have a player with full volume, but also mutedBetween0.0to1.0videoCreatedTimeNumberThe timestamp that corresponds to the creation of the videovideoDurationNumberThe duration time of the video resource in secondsvideoIdStringThe unique Id of the videovideoIsPasswordRequiredBooleanIf the video required a password to be read”true”,”false”videoOwnerIdStringThe id of the owner of the videovideoOwnerScreennameStringThe screen name of the owner of the videovideoOwnerUsernameStringThe user name of the owner of the videovideoQualitiesListArrayThe video qualities that are availablevideoQualityStringThe quality value of the video loadedvideoSubtitlesStringThe language code of the subtitle track that is currently enabledvideoSubtitlesListArrayThe language codes of the subtitle tracks which are available for the current truyền thông resourcevideoTimeNumberThe current playback position of the video in secondsvideoTitleStringThe title of the video loadedvideoIsCreatedForKidsStringIf the video is created for Children

    Example player state

    “adAdvertiserName”: “Dailymotion advertiser”,
    “adCompanion”: null,
    “adCreativeAdId”: null,
    “adCreativeId”: “video”,
    “adDescription”: “Dailymotion ad”,
    “adDuration”: 15.07,
    “adEndedReason”: null,
    “adError”: null,
    “adId”: “32251”,
    “adIsPlaying”: true,
    “adIsSkippable”: true,
    “adPosition”: “midroll”,
    “adSkipOffset”: 0,
    “adTime”: 6.42,
    “adTitle”: “Dailymotion_ad”,
    “playerAreControlsEnabled”: true,
    “playerAspectRatio”: “16:9”,
    “playerError”: null,
    “playerIsAlertDialogDisplayed”: false,
    “playerIsBuffering”: false,
    “playerIsCriticalPathReady”: true,
    “playerIsMuted”: null,
    “playerIsNavigationEnabled”: true,
    “playerIsPipNativeSupported”: true,
    “playerIsPlaybackAllowed”: true,
    “playerIsPlaying”: true,
    “playerIsReplayScreen”: false,
    “playerIsStartScreen”: false,
    “playerIsViewable”: true,
    “playerNextVideo”: “x81ixxp”,
    “playerPipDisplay”: “largeViewport”,
    “playerPipIsExpanded”: false,
    “playerPipStatus”: “enabled”,
    “playerPlaybackPermissionReason”: “allowed”,
    “playerPresentationMode”: “inline”,
    “playerPrevVideo”: null,
    “playerScaleMode”: “fit”,
    “playerVolume”: 1,
    “videoCreatedTime”: 1551103337,
    “videoDuration”: 214.06,
    “videoId”: “x730nnd”,
    “videoIsPasswordRequired”: false,
    “videoOwnerId”: “x23rwb7”,
    “videoOwnerScreenname”: “Player team”,
    “videoOwnerUsername”: “player-team”,
    “videoQualitiesList”: [“1080”, “720”, “480”, “380”, “240”, “144”],
    “videoQuality”: “Auto”,
    “videoSubtitles”: “en”,
    “videoSubtitlesList”: [“fr”, “en”],
    “videoTime”: 60.12,
    “videoTitle”: “Dailymotion video”,

    

    Access the Player settings

    Its possible to retrieve the initial player configuration including theplayerIDusing thegetSettings()method. On resolve, this returns an object representation of the player configuration.

    Example of logging the player settings to the console

    dailymotion
    .getPlayer()
    .then((player) =>
    console.log(player.getSettings());
    )
    .catch((e) => console.error(e));

    Example player settings object

    “id”: “PLAYERID”,
    “aspectRatio”: “16:9”,
    “autostart”: “firstTimeViewable”,
    “color”: “”,
    “enableAutoNext”: true,
    “enableControls”: true,
    “enableDMLogo”: true,
    “enableInfo”: true,
    “enableQueue”: true,
    “enableSharing”: true,
    “enableSharingUrlLocation”: true,
    “enableChannelLink”: true,
    “enableVideoTitleLink”: true,
    “enableStartPipExpanded”: true,
    “enableHeaderDetectionOverlap”: false,
    “pip”: “off”

    

    Please check out the player embed collection on ourDailymotion codepen accountto see some useful code snippets that you can test and use within your project.

    In order to benefit from the best performance of the new player solution, please consider the following tips from our engineers.

  • Add preload and preconnect directives towards the top of thesection of the HTML response.
  • Load the player or player library directly, avoid using any third-party solution such as Google Ad Manager. Player libraries and the player embed script should be added to thesection of your document.
  • Load the player library in the section, ensure any code that interacts with the Player API is loaded after it.
  • The Dailymotion player is a sophisticated piece of software that handles several complex processes for you (adaptive streaming, ads monetization, tracking and many more). The video player loading should be prioritized in front of other resources where possible. Its advisable to reduce the amount of JavaScript executed before the player loads; use the”defer”attribute on non-critical scripts, or load them dynamically via JavaScript instead of HTML.
  • Please be aware that we are in the process of discontinuing tư vấn for the below products. We recommend all partners to utilize the latest integration methods outlined in the embed the player on web section foundhere. The following section outlines the functionality and player services that are considered to be no longer available.

    JavaScript Player API Reference (legacy)

    Our Player API allows you to interact with and take complete control of the Dailymotion video player. It can be accessed through our SDKs and provides access to all the player methods, events and properties. Our APIs allow you to create a unique and personalized experience.

    Methods (legacy)

    Before sending any API commands to a player instance, you should wait for theapireadyplayer sự kiện to be fired.

    MethodInfoExampleDM.player()Create a player instance. The SDK will take care of generating and injecting an iframe into the div placeholderDM.player(document.getElementById(player)load(String)Load the player with a video ID (e.g. x7tgad0)player.load(x7tgad0)load(video: String, playlist: String, autoplay : Boolean, start : Float)Load the player with a video and configure other runtime time parametersplayer.load( video: x7tgad0, playlist: x5zhzj, autoplay:false, start: 5)play()Start or resume video playbackplayer.play()pause()Pause video playbackplayer.pause()setVolume(Float)Set the players volume to the specified level between 0 & 1. ie, 0.5 = 50%player.setVolume(0.5)setSubtitles(String)Activate subtitles track to a specified language if availableplayer.setSubtitle(fr)seek(Float)Seek to the specified time in video playback in secondsplayer.seek(30)setQuality(String)Set the videos quality to the specified quality[240, 380, 480, 720, 1080, 1440, 2160 default]player.setQuality(720)setMuted(Boolean)Enable or disable muteplayer.setMuted(true)setFullscreen(Boolean)Enable or disable fullscreen modeplayer.setFullscreen(true)setControls(Boolean)Enable or disable the players controls UIplayer.setControls(false)togglePlay()Switch the players playback state between play/pauseplayer.togglePlay()toggleControls()Switch the players controls UI between enabled/disabledplayer.toggleControls()toggleMuted()Switch the players Mute state between muted/unmutedplayer.toggleMuted()watchOnSite()Redirect to watch video on Dailymotion.complayer.watchOnSite()setAdsConfig()Dynamically update the advertising parameter value, use the method to send a new value which then gets updated when the player loads the next video fileplayer.setAdsConfig(ads_params: your_ads_params)

    Events (legacy)

    The player emits events relating to the change of the player state, video playback and ad content. To listen to specific player events, you must integrate the player using our SDKs.

    Player events (legacy) Player eventDescriptionapireadySent when the player is ready to accept API commands. Do not try to call functions before receiving this eventcontrolschangeSent when the availability to use our player controls changes (visible or hidden)startSent the first time the player attempts to start the playback, either because of user interaction, an autoplay parameter or an API call (e.g play(), load(), etc.)endSent when playback of the content video, and eventual post-roll ad video, is completedendedDeprecated. Use video_end insteaderrorSent when the player triggers an error. Please see error codesherefullscreenchangeSent when the player enters or exits the fullscreen stateplayback_readySent every time a video is ready to play, or started playing (depending on autoplay settings, and their resolution by the browser), or is unable to play (blocked, restricted, unavailable). Listen to this sự kiện if you want to defer doing network-heavy and JavaScript-heavy work, to allow the optimal delivery of the first frames of the video to the useseekingSent when the player starts to seek to another position in the video timelineseekedSent when the player has completed a seeking operationvideochangeSent when a new video has been loaded in the player. (e.g. after calling load(videoId,[params]), or at player start-up)volumechangeSent when the volume or mute state changesVideo events (legacy) Video eventDescriptionvideo_startSent when the player begins playback of the content videovideo_endSent when the player completes playback of the content videopauseSent when the video playback has pausedplaySent when the playback state of the content video is no longer paused, as a result of the play method or the autoplay attributeplayingSent when the content video starts playing, after the play or waiting eventdurationchangeSent when the duration property of the video becomes available or changes after a new video loadloadedmetadataSent when the videos metadata is loadedwaitingSent when the player has to temporarily stop video playback for further buffering of contentsubtitlechangeSent when the current subtitle changessubtitlesavailableSent when subtitles are available, wait until theapireadyevent to set subtitle via the APIqualitiesavailableSent when video qualities are availablequalitieschangedSent when the video quality changestimeupdateSent when the playback position changesprogressSent when the browser is fetching the truyền thông dataplayback_resolutionSent each time any playback request has failed or if the initial playback attempt has succeeded. On dispatch the status and reason values can be accessed from thedata.detailobject.Ad events (legacy) Ad eventDescriptionad_startSent when the player begins playback of an ad videoad_endSent when the player completes playback of an ad videoad_pauseSent when the player pauses an adad_playSent when the ad playback startsad_timeupdateSent when the playback position of an ad changesad_companionsSent when a companion ad is received. Companion ads should be played in sync with the main ad (linear/non-linear) by listening to events ad_start and ad_endad_clickSent when a user clicks on a video adad_loadedSent when the player has loaded an advertisement in full or to the extent it can begin playbackad_impressionSent when the first frame of the advertisement has been displayedad_bufferStartSent when the advertising playback has stopped due to bufferingad_bufferFinishSent when the advertising playback has resumed due to the end of buffering

    Player Properties (legacy)

    The player API grants access to information about the players current state and specific properties. The following properties will be maintained currently for utilization for player customization for AMP embeds and when using Android & iOS SDKs.

    PropertyInfoTypebufferedTimeThe part of the truyền thông resource that has been downloaded in seconds.NumbercontrolsWhether the player controls are enabledBooleancurrentTimeThe current playback position in seconds of an ad or a video resourceNumberdurationThe duration time of the video resource in secondsNumberendedWhether the video has endedBooleanerrorContains error code, title and message about the last error that occurred in the playerObjectfullscreenWhether the player is in full-screen modeBooleanmutedWhether the player is currently mutedBooleanpausedWhether the current playback state is pausedBooleanqualitiesThe video qualities that are availableArrayqualityThe current quality value of the video element loadedStringseekingWhether the video element is seekingBooleansubtitleThe subtitle language code that is currently enabledStringsubtitlesThe available subtitle language codes of the truyền thông fileArrayvolumeThe current volume level. Between 0.0 to 1.0. The volume and mute params operate separately, therefore, you could have a player with full volume, but also mutedNumbervideoContains the video ID and titleObjectcompanionAdsAn array of parsed companion ad creativesArrayloopWhether the player is currently in loop modeBoolean

    Player Parameters (legacy)

    The below parameters can be utilised still with our Android SDK, iOS SDK & AMPs embeds. However, we are in the process of phasing them out with future SDK updates.

    Use the below parameters to customize your player via the iframe or SDK embed.

    ParameterInfoTypeautoplayAutomatically attempt to start playback with sound, if it is blocked by the browser, the player will force the video muteBooleancontrolsWhether to display the player controls, true by defaultBooleanidID of the player unique to the page to be passed back with all API messagesStringmuteWhether to mute the videoBooleanqualitySpecify the suggested playback quality for the videoNumbersharing-enableWhether to display the sharing buttonBooleanstartSpecify the time (in seconds) from which the video should start playingNumbersubtitles-defaultSpecify the default selected subtitles languageStringsyndicationPass your syndication key to the playerStringui-highlightChange the default highlight color used in the controls (hex value without the leading #). Color set in the Partner HQ will override this paramStringui-logoWhether to display the Dailymotion logoBooleanui-start-screen-infoWhether to show video information (title and owner) on the start screenBooleanplaylistSpecify a playlist ID to populate the Up Next Queue with videos from a playlistStringfullscreenWhether to display the fullscreen buttonBooleanscaleModeSpecify the default focus of the player in order to reframe and refocus on a specific area in the video. To be used for scaling and repurposing of videos between different aspect ratios for example landscape to portrait. Values ( fit, fill, fillLeft, fillRight, fillTop, fillBottom )StringloopWhether to loop a video or an entire playlist. A video embed will start over again automatically. A playlist embed will start to play from the first item in the playlist after the entire playlist has finishedBoolean

    2022-01-26

    • New property videoIsCreatedForKids added to the player state.

    2022-12-17

    • JavaScript Player API Expose a new player eventPLAYER_HEAVYADSINTERVENTION.

    2021-12-02

    • New Player Embed global release

    Reply
    9
    0
    Chia sẻ

    Video full hướng dẫn Share Link Tải Autoplay true ?

    – Một số từ khóa tìm kiếm nhiều : ” Video full hướng dẫn Autoplay true tiên tiến và phát triển nhất , Share Link Down Autoplay true “.

    Hỏi đáp vướng mắc về Autoplay true

    Bạn trọn vẹn có thể để lại Comments nếu gặp yếu tố chưa hiểu nghen.
    #Autoplay #true Autoplay true

    Phương Bách

    Published by
    Phương Bách