# Controlling the player


You receive the player control object from [`create()`](https://docs.kinescope.com/player-docs/embedding/iframe-api-create-player/#create). Use it to start playback, update settings, and subscribe to events.

## Quick example

```js
player.on(player.Events.Playing, () => {
  console.log('playback started')
})

await player.setVolume(0.5)
await player.play()
```

## Properties {#events}

| Property | Type | Description |
| :--- | :--- | :--- |
| `Events` | `IframePlayerApi.Events` | Enumeration of [player events](#event-data) |

## Methods

### Event subscriptions

| Method | Returns | Description |
| :--- | :--- | :--- |
| <a id="on"></a>`on(type, listener)` | `this` | Subscribe to an [event](#event-data) |
| <a id="once"></a>`once(type, listener)` | `this` | Subscribe to an event once |
| <a id="off"></a>`off(type, listener)` | `this` | Unsubscribe from an event |

### Playback

| Method | Returns | Description |
| :--- | :--- | :--- |
| <a id="play"></a>`play()` | `Promise<void>` | Start playback |
| <a id="pause"></a>`pause()` | `Promise<void>` | Pause playback |
| <a id="stop"></a>`stop()` | `Promise<void>` | Stop playback and seek to the beginning |
| <a id="seekTo"></a>`seekTo(time)` | `Promise<void>` | Seek to a time in seconds |
| <a id="isPaused"></a>`isPaused()` | `Promise<boolean>` | Check whether playback is paused |
| <a id="isEnded"></a>`isEnded()` | `Promise<boolean>` | Check whether playback has ended |
| <a id="getCurrentTime"></a>`getCurrentTime()` | `Promise<number>` | Current time in seconds |
| <a id="getDuration"></a>`getDuration()` | `Promise<number>` | Video duration in seconds |
| <a id="getPlaybackRate"></a>`getPlaybackRate()` | `Promise<number>` | Playback speed. `1` is the normal speed |
| <a id="setPlaybackRate"></a>`setPlaybackRate(value)` | `Promise<void>` | Set the playback speed |

### Audio

| Method | Returns | Description |
| :--- | :--- | :--- |
| <a id="mute"></a>`mute()` | `Promise<void>` | Mute the player |
| <a id="unmute"></a>`unmute()` | `Promise<void>` | Unmute the player |
| <a id="isMuted"></a>`isMuted()` | `Promise<boolean>` | Check whether the player is muted |
| <a id="getVolume"></a>`getVolume()` | `Promise<number>` | Volume from `0` to `1` |
| <a id="setVolume"></a>`setVolume(value)` | `Promise<void>` | Set the volume from `0` to `1` |

### Quality and subtitles

| Method | Returns | Description |
| :--- | :--- | :--- |
| <a id="getVideoQualityList"></a>`getVideoQualityList()` | `Promise<VideoQuality[]>` | List of available [quality levels](https://docs.kinescope.com/player-docs/optimization/#video-quality) |
| <a id="getVideoQuality"></a>`getVideoQuality()` | `Promise<VideoQuality>` | Current [quality](https://docs.kinescope.com/player-docs/optimization/#video-quality) |
| <a id="setVideoQuality"></a>`setVideoQuality(quality)` | `Promise<void>` | Set the [quality](https://docs.kinescope.com/player-docs/optimization/#video-quality) |
| <a id="enableTextTrack"></a>`enableTextTrack(lang)` | `Promise<void>` | Enable subtitles in the `lang` language |
| <a id="disableTextTrack"></a>`disableTextTrack()` | `Promise<void>` | Disable subtitles |

### Fullscreen and PiP

| Method | Returns | Description |
| :--- | :--- | :--- |
| <a id="isFullscreen"></a>`isFullscreen()` | `Promise<boolean>` | Check whether fullscreen mode is active |
| <a id="setFullscreen"></a>`setFullscreen(fullscreen)` | `Promise<void>` | Enable or disable fullscreen mode |
| <a id="isPip"></a>`isPip()` | `Promise<boolean>` | Check whether Picture-in-Picture is active |
| <a id="setPip"></a>`setPip(pip)` | `Promise<void>` | Enable or disable PiP |

### Playlist and CTA

| Method | Returns | Description |
| :--- | :--- | :--- |
| <a id="getPlaylistItem"></a>`getPlaylistItem()` | `Promise<{ id?: string } \| undefined>` | Current playlist video |
| <a id="switchTo"></a>`switchTo(id, options?)` | `Promise<void>` | Switch to the video with this `id` and optional [options](#switchTo-options) |
| <a id="next"></a>`next()` | `Promise<void>` | Switch to the next playlist video |
| <a id="previous"></a>`previous()` | `Promise<void>` | Switch to the previous playlist video |
| <a id="closeCTA"></a>`closeCTA()` | `Promise<void>` | Close the CTA screen. `@experimental` |
| <a id="setPlaylistItemOptions"></a>`setPlaylistItemOptions(options)` | `Promise<void>` | Set the current video options with [PlaylistItemOptions](#setPlaylistItemOptions-options) |

#### switchTo options {#switchTo-options}

```ts
interface SwitchToOptions {
  autoPlay?: boolean;
  time?: number;
}
```

#### setPlaylistItemOptions parameters {#setPlaylistItemOptions-options}

Set the title, subtitles, chapters, CTA, DRM, and advertising for the current video.

```ts
interface AdItemYaOptions {
  // See https://yandex.ru/dev/video-sdk/doc/ru/sdk-html5/AdConfig-interface
  adConfig: Record<string, unknown>;
  // See https://yandex.ru/dev/video-sdk/doc/ru/sdk-html5/PlaybackParameters-interface
  playbackParameters?: Record<string, unknown>;
}

type AdItemOptions =
  | {
      /** Advertising tag URL. */
      adTagUrl: string | string[];
    }
  | {
      /** @experimental Complete advertising tag text. */
      adTag: string | string[];
    }
  | {
      /** @experimental Google IMA request object (`adsRequest`). */
      adsRequest: Record<string, unknown>;
    }
  | {
      /** @experimental Settings for Yandex Video Ads SDK. */
      yaOptions: AdItemYaOptions | AdItemYaOptions[];
    };

interface PlaylistItemOptions {
  /** Video title. Displayed at the top of the player. */
  title?: string;

  /** Video subtitle. Displayed below the main title. */
  subtitle?: string;

  /** Video poster image. */
  poster?: string;

  /** Subtitles (video text tracks). */
  vtt?: {
    /** Title */
    label: string;
    /** Subtitle file URL */
    src: string;
    /** Subtitle language */
    srcLang: string;
  }[];

  /** Chapters that divide the video timeline. */
  chapters?: {
    /** Time in seconds */
    position: number;
    /** Title */
    title: string;
  }[];

  /** Additional downloadable materials. */
  files?: {
    list: {
      name: string;
      url: string;
      mime: string;
      size?: number;
    }[];
    archiveUrl?: string;
  };

  /** @experimental Time-based bookmarks. */
  bookmarks?: {
    id: string;
    /** Time in seconds. */
    time: number;
  }[];

  /**
   * @experimental Calls to action (CTA).
   * `type`: overlay | popup | panel | banner | buttons | leadgen. Default: overlay.
   * See all fields by type in the CTA section: /player-docs/cta/
   */
  cta?: {
    id: string;
    type?: 'overlay' | 'popup' | 'panel' | 'banner' | 'buttons' | 'leadgen';
    title?: string;
    description?: string;
    skippable?: boolean;
    button?: { text: string; style?: CSSProperties; url?: string };
    trigger: {
      percentages?: number[];
      timePoints?: number[];
      pause?: boolean;
    };
    // + fields for the selected type (link, position, list, fields, url, …)
  }[];

  /** DRM. */
  drm?: {
    auth?: {
      /** Custom authorization token for license requests. */
      token?: string;
    };
  };

  /** Advertising. See [Advertising](https://docs.kinescope.com/player-docs/advertising/). */
  ad?:
    | AdItemOptions
    | (AdItemOptions & {
        /** Advertising trigger. */
        trigger: {
          /** Current time percentage. For example: `[0, 100]`. */
          percentages?: number[];
          /** Time points in seconds. For example: `[60, 600]`. */
          timePoints?: number[];
          /** Repeat interval in seconds. For example, `600` means every 10 minutes. */
          interval?: number;
        };
      })[];
}
```

### Settings and destruction

| Method | Returns | Description |
| :--- | :--- | :--- |
| <a id="setOptions"></a>`setOptions(options)` | `Promise<void>` | Update player options with [UpdatablePlayerOptions](#setOptions-options) |
| <a id="destroy"></a>`destroy()` | `Promise<void>` | Remove the player `<iframe>` from the DOM |

#### setOptions parameters {#setOptions-options}

```ts
interface UpdatablePlayerOptions {
  /** UI settings */
  ui?: {
    /** Watermark. */
    watermark?: {
      /** Text */
      text: string;
      /**
       * - `stripes` - display in lines;
       * - `random` - display in random locations;
       * Default: `random`.
       */
      mode?: 'stripes' | 'random';
      /** Text scaling factor based on the player size. Default: `0.25`. */
      scale?: number;
      /** Show and hide duration in milliseconds. If omitted, the text remains visible. */
      displayTimeout?: number | { visible: number; hidden: number };
    };
  };
}
```

Example:

```ts
player.setOptions({ ui: { watermark: { text: 'watermark' } } })
```

## Player events {#player-events}

Each handler receives an [event object](#event-object). The `data` field depends on the event type and may be absent.

### Playback lifecycle {#lifecycle}

The main events occur in this order:

```
create → Loaded → Play → Playing → TimeUpdate* → Pause / Ended → Destroy
```

| Event | When it occurs |
| :--- | :--- |
| `Loaded` | The player is ready for playback. With `preload: false`, this occurs when playback starts |
| `Play` | Playback is requested with the Play button or `play()` |
| `Playing` | Playback has started |
| `TimeUpdate` | Periodically during playback |
| `Waiting` | The player is buffering |
| `Pause` / `Ended` | Playback is paused or the video ends |
| `Destroy` | The player is removed from the DOM |

When the playlist video changes, `CurrentTrackChanged` occurs first, followed by `Loaded` for the new video.

### Event object {#event-object}

```ts
{
  /** Event type */
  type: IframePlayerApi.Events;
  /** Event data. Its structure depends on the event type and may be absent. */
  data: Data;
  /** Player control object associated with the event */
  target: IframePlayerApi;
}
```

### Event enumeration {#event-data} <a id="EventListeners"></a>

| Event | Data | Description |
| :--- | :--- | :--- |
| <a id="Events.Loaded"></a>`Loaded` | `{ currentTime, duration, quality, audioTrack }` | Video data loaded and the player is ready. With `preload: 'none'`, this occurs when playback starts |
| <a id="Events.CurrentTrackChanged"></a>`CurrentTrackChanged` | `{ item: { id?: string } }` | Current track changed |
| <a id="Events.SizeChanged"></a>`SizeChanged` | `{ width, height }` | Player size changed |
| <a id="Events.QualityChanged"></a>`QualityChanged` | `{ quality }` | Video quality changed |
| <a id="Events.Play"></a>`Play` | — | Playback requested |
| <a id="Events.Playing"></a>`Playing` | — | Playback started |
| <a id="Events.Pause"></a>`Pause` | — | Playback paused |
| <a id="Events.Ended"></a>`Ended` | — | Playback ended |
| <a id="Events.TimeUpdate"></a>`TimeUpdate` | `{ currentTime, percent }` | Current time changed |
| <a id="Events.Waiting"></a>`Waiting` | — | Buffering |
| <a id="Events.Progress"></a>`Progress` | `{ bufferedTime }` | Media resource is loading |
| <a id="Events.DurationChange"></a>`DurationChange` | `{ duration }` | Video duration changed |
| <a id="Events.VolumeChange"></a>`VolumeChange` | `{ volume, muted }` | Volume level changed |
| <a id="Events.PlaybackRateChange"></a>`PlaybackRateChange` | `{ playbackRate }` | Playback speed changed |
| <a id="Events.Seeked"></a>`Seeked` | — | Seek completed |
| <a id="Events.SeekChapter"></a>`SeekChapter` | `{ position }` | Playback moved to a chapter |
| <a id="Events.FullscreenChange"></a>`FullscreenChange` | `{ isFullscreen, type, video? }` | Fullscreen mode changed. `type`: `'video' \| 'pseudo' \| 'native'`. `video` is `@deprecated`; use `type` |
| <a id="Events.PipChange"></a>`PipChange` | `{ isPip }` | Picture-in-Picture mode. [Can I use](https://caniuse.com/picture-in-picture) |
| <a id="Events.CallAction"></a>`CallAction` | `{ id }` | CTA activated. `@experimental` |
| <a id="Events.CallBookmark"></a>`CallBookmark` | `{ id, time }` | Bookmark selected. `@experimental` |
| <a id="Events.AdBreakStateChanged"></a>`AdBreakStateChanged` | `{ active }` | Ad break state changed. `@experimental` |
| <a id="Events.ControlBarVisibilityChanged"></a>`ControlBarVisibilityChanged` | `{ visible }` | Control bar visibility changed. `@experimental` |
| <a id="Events.Error"></a>`Error` | `{ error }` | Critical error |
| <a id="Events.Destroy"></a>`Destroy` | — | Player removed from the DOM |

Events are available as `player.Events.<Name>`. For example, use `player.Events.Playing`.

## Next steps

- [Playlists](https://docs.kinescope.com/player-docs/playlists/) — dynamic and static playlists
- [CTA](https://docs.kinescope.com/player-docs/cta/) — calls to action displayed over a video
- [Advertising](https://docs.kinescope.com/player-docs/advertising/) — VAST/IMA and triggers
- [player-iframe-api-loader](https://docs.kinescope.com/player-docs/libraries/player-iframe-api-loader/) — npm loader and types
- [Automatic connection](https://docs.kinescope.com/player-docs/embedding/iframe-api-auto-connect/) — API for an existing iframe
- [Create a player](https://docs.kinescope.com/player-docs/embedding/iframe-api-create-player/) — factory and `CreateOptions`

