my.createVideoContext

The my.createVideoContext API is used to play videos in mini-programs. You can call this API to input videoId and return videoContext, where videoId refers to the ID attribute that is customized by the developer in the corresponding video tab, and you can operate a video component through videoContext.

Before you begin

Before calling the my.createVideoContext API, you need to take the following things into consideration:

  • The SDK version needs to be at least GriverVersion 2.48.0. If the version is lower than GriverVersion 2.48.0, calling this API can cause app crashes.
  • The mini program core library (Appx) needs to be the 2.0 version. For more information about how to update Appx to 2.0, contact your Solution Architect for the documentation.

Note: To learn about what versions the Appx and the SDK that you integrate are, refer to How to obtain your current versions.

  • CSS animations are not supported.
  • Supported video package format for both iOS and Android: MP4
  • Supported encoding format for both iOS and Android: H.264

Effect

The following figure shows the effect of the video playback.

1677554272234-afa0185f-8ea1-40ee-9e12-68623a034b84.png

Parameters

The following table lists the request parameters of the my.createVideoContext API.

Property

Type

Description

scr

String

The URL of the video resource. Only HTTPS URLs are supported.

poster

String

The URL of the video poster. If this parameter is not specified, the poster is by default set as the first frame of the video.

poster-size

String

The size to display the video poster when the aspect ratio of the poster is inconsistent with the aspect ratio of the video.

Specify this parameter by following the same rule to specify the background-size parameter. For more information about how to specify background-size, see Sizing Images: the 'background-size' property.

Default value: contain

initial-time

String

The specific time when the video starts to play. The unit of this parameter is s (second).

controls

Boolean

Indicates whether to display the default playback controls, such as the playback button, the pause button, the progress bar, and the video length.

Default value: true

autoplay

Boolean

Indicates whether to play the video automatically.

Default value: false

direction

Number

The direction when the video is played in full screen. Valid values are:

  • 0: indicates the video is played in a vertical direction.
  • 90: indicates the video is rotated in the anticlockwise direction by 90 degrees.
  • -90: indicates the video is rotated in the clockwise direction by 90 degrees.

If this parameter is not specified, the direction is automatically determined by the aspect ratio of the video.

loop

Boolean

Indicates whether to loop the video.

Default value: false

muted

Boolean

Indicates whether to play the video in mute.

Default value: false

onPlay

EventHandler

Plays the video when the video starts or continues to play.

onPause

EventHandler

Pauses the video when the video pauses to play.

onEnded

EventHandler

Ends the video when the video finishes playing.

onTimeUpdate

EventHandler

Updates the time when the video is being played.

The returned code sample can be as follows: event.detail = {currentTime: 'current position of the video playback',userPlayDuration:'user watching duration',videoDuration:'video length'}

onLoading

EventHandler

Loads the video when the video is being loaded.

onError

EventHandler

Triggers the error code when an error occurs when the video is being played. For more information about error codes, see Error codes.

onFullScreenChange

EventHandler

Enters or quits the full-screen mode.

The returned code sample can be as follows: event.detail = {fullScreen, direction}, where direction needs to be set as vertical or horizontal.

onUserAction

EventHandler

The user operates the video playback.

The returned code sample can be as follows: event.detail = {tag:"mute", value:0}, where tag is the element that the user operates. Valid values of tag are:

  • play: indicates the button on the bottom to play the video.
  • centerplay: indicates the button in the center to play the video.
  • mute: indicates the button to mute the video.
  • fullscreen: indicates the button to make the video full-screen.

onStop

EventHandler

Stops playing the video.

onRenderStart

EventHandler

Starts playing the video when the video is loaded.

Error codes

The following table lists the error codes, their descriptions, further actions, and whether the error codes are supported by the Android or iOS system.

Error code

Description

Further action

Android

iOS

1

Unknown exception

Try the API call again.

  • ✅
  • ✅

1002

Player system error

Check the player system.

  • ✅
  • ✅

1005

Network error

Check the network.

  • ✅
  • 🔲

1006

Metadata error

Check the metadata.

  • ✅
  • ✅

1007

Player initialization error

Check the player and initialize it again.

  • ✅
  • 🔲

3001

Audio rendering error

Check if the audio resource meets the requirements.

  • ✅
  • 🔲

3002

Hardware decoding error

Check if the hardware decoding works.

  • ✅
  • 🔲

Sample codes

.axml

Refer to the following sample to learn about how to use AXML to call the API.

copy
<view style="width:100%">
  <video
    style="width:100%"
    id="myVideo"
    src="{{video.src}}"
    poster-size="{{video.posterSize}}"
    poster="{{video.poster}}"
    controls="{{video.showAllControls}}"
    loop="{{video.isLooping}}"
    muted="{{video.muteWhenPlaying}}"
    autoplay="{{video.autoPlay}}"
    direction="{{video.directionWhenFullScreen}}"
    initial-time="{{video.initTime}}"
    onPlay="onPlay"
    onPause="onPause"
    onTap="onTap"
    onEnded="onEnded"
    onError="onError"
    onRenderStart="onRenderStart"
    onTimeUpdate="onTimeUpdate"
    onUserAction="onUserAction"
    onFullScreenChange="onFullScreenChange"
    onLoading="onLoading"
  ></video>
  <button type="default" size="defaultSize" onTap="play">Play</button>
  <button type="default" size="defaultSize" onTap="pause">Pause</button>
  <button type="default" size="defaultSize" onTap="stop">stop</button>
  <button type="default" size="defaultSize" onTap="seek">seek</button>
  <button type="default" size="defaultSize" onTap="requestFullScreen">
    requestFullScreen
  </button>
  <button type="default" size="defaultSize" onTap="exitFullScreen">
    exitFullScreen
  </button>
  <button type="default" size="defaultSize" onTap="mute">mute</button>
  <view style="height:1000">
  </view>
</view>

.js

Refer to the following sample to learn about how to use JavaScript to call the API.

copy
Page({
  data: {
    video: {
      src: 'https://xxx.mp4',
      poster: "https://xxx.jpg",
      posterSize: "contain", //contain, cover
      showAllControls: false,
      isLooping: false,
      muteWhenPlaying: false,
      initTime: 0,
      autoPlay: false,
      directionWhenFullScreen: 0
    }
  },
  onLoad() {
    this.videoContext = my.createVideoContext('myVideo');
  },
  play() {
    this.videoContext.play();
  },
  pause() {
    this.videoContext.pause();
  },
  stop() {
    this.videoContext.stop();
  },
  seek() {
    this.videoContext.seek(15);
  },
  requestFullScreen() {
    this.videoContext.requestFullScreen({
      direction: -90,
    });
  },
  exitFullScreen() {
    this.videoContext.exitFullScreen();
  },
  mute() {
    this.videoContext.mute(false);
  },
  onPlay(e) {
    console.log('video: onPlay');
  },
  onPause(e) {
    console.log('video: onPause');
  },
  onEnded(e) {
    console.log('video: onEnded');
  },
  onError(e) {
    console.log('video: onPlayError, e=' + JSON.stringify(e));
  },
  onRenderStart(e) {
    console.log('video: onRenderStart');
  },
  onTimeUpdate(e) {
    // console.log('video: onTimeUpdate: ' +  JSON.stringify(e));
  },
  onUserAction(e) {
   console.log('video: onUserAction: ' +  JSON.stringify(e));
  },
  onTap(e) {
    console.log('video: onTap: ' +  JSON.stringify(e));
  },
  onFullScreenChange(e) {
    console.log('video: onFullScreenChange: ' +  JSON.stringify(e));
  },
  onLoading(e) {
    console.log('video: onLoading: ' +  JSON.stringify(e));
  },
});

FAQs

When the user watches a video that was loaded and watched once in the video component, does the video need to be loaded again?

If the video is played in a loop, the cache of the video is pulled when the user watches it again; otherwise, the video needs to be loaded again.

When are videos in the cache cleared?

When the page or the mini program is closed, videos in the cache are cleared.

How can the mini program obtain the video length?

The mini program can obtain the video length via the onTimeUpdate parameter.

How can I troubleshoot?

Take the following steps for troubleshooting:

  1. Ensure that the AXML code contains the id parameter, for example, id="your-video-id".
  2. Ensure that the value of the id parameter is not a reserved word, such as drawing-area-root, content-root, RenderView, TileGrid container, pageTiledBacking containment, or ancestor clipping.
  3. Ensure that the value of the id parameter consists of only letters, -, and _, and does not contain special characters such as * and /.
  4. Ensure that the value of the id parameter is not too long due to containing the mini program ID or the current Unix timestamp.
  5. Ensure that the value of the id parameter is unique. For example, if the value of id is main-video, do not specify any similar value such as main-video-wrapper; otherwise, the WKCompositingView is generated, which can cause errors in the position of the components on the same layer.
  6. Try the raw-controls property to solve the problem where the video component is wrongly positioned on a high layer in your mini program.

Appendix

How to obtain your current versions

Upgrades of the minor or patch version number of the mini program Appx or SDK bring new or enhanced functions on basic elements, APIs, or performance characteristics. To ensure that these functions can work in your mini program, you need to learn about what versions you currently integrate and consider compatibility if necessary.

Refer to the following sample code to obtain the current versions of your mini program Appx and SDK, where the versions are both strings in the format of major.minor.patch.

copy
/**
 * @description Appx version
 * @example "2.8.0"
 */
const sdkVersion = my.SDKVersion;
/**
 * @description SDK version
 * @example "2.48.0"
 */
const griverVersion = my.getSystemInfoSync().griverVersion;

Moreover, you can call the comparison function to compare the current versions you integrate with the lowest versions that are required in the Begin you begin section. The following code shows an example of calling the comparison function.

copy
/**
 * @param {string} v1
 * @param {string} v2
 * @returns {-1 | 0 | 1}
 */
function compareVersion(v1, v2) {
  var s1 = v1.split(".");
  var s2 = v2.split(".");
  var len = Math.max(s1.length, s2.length);
  for (let i = 0; i < len; i++) {
    var num1 = parseInt(s1[i] || "0");
    var num2 = parseInt(s2[i] || "0");
    if (num1 > num2) {
      return 1;
    } else if (num1 < num2) {
      return -1;
    }
  }
  return 0;
}
// v1 > v2 return 1
1 === compareVersion("2.6.8", "1.24.10");
// v1 = v2 return 0
0 === compareVersion("2.6", "2.6.0");