Integrate the preview component web SDK

Updated at:

Integrate the video editing Web SDK preview component into your frontend pages to preview timelines independently.

Usage notes

This topic uses version 5.2.2 of the video editing Web SDK. Starting from version 5.0.0, a license is required. Get the latest version from Video Editing Projects — Help Information.

You can obtain a license in two ways:

Method 1 (Recommended): Subscribe to Enterprise Standard Edition or Enterprise Ultimate Edition by year, and you will receive a cloud clip WebSDK License (including preview WebSDK integration license). For purchase instructions, please refer Billing overview.

Alternatively, purchase a web SDK license separately for CNY 20,000/year. Submit a ticket for the purchase link.

Environment requirements

The preview component relies on browser security policies. Access the page through an HTTP service such as http://localhost:7001/. Do not open the HTML file from the local file system.

Procedure

  1. Include the SDK files.

    In your HTML file, include the preview component CSS file in the <head> tag.

    <head>
      <link rel="stylesheet" href="https://g.alicdn.com/thor-server/video-editing-websdk/5.2.2/player.css">
    </head>

    Add a <div> element in the <body> tag to mount the preview component. Before the closing </body> tag, include the SDK JavaScript file and a <script> tag for initialization code.

    <body>
      <div id="player-wrapper" style="height:500px"></div> // You can change the container height as needed.
      <script src="https://g.alicdn.com/thor-server/video-editing-websdk/5.2.2/player.js"></script>
      <script>
        // Place your SDK initialization code here.
      </script>
    </body>
  2. Initialize the preview component.

    const player = new window.AliyunTimelinePlayer({
      container: document.querySelector('#player-wrapper'),
      licenseConfig: {
        rootDomain: "", // The root domain for the license, for example, abc.com.
        licenseKey: "", // The licenseKey you applied for. If no licenseKey is configured, a watermark appears in the preview. Without a license, you can only preview on the localhost domain.
      },
      timeline: { // Optional.
        VideoTracks: [], // VideoTracks content omitted.
        AudioTracks: [], // AudioTracks content omitted.
        AspectRatio: '16:9',
      },
      getMediaInfo: (mediaId) => {
        return Promise.resolve('https://example.com/url/for/this/media.mp4');
      },
    });
    • Pass a PlayerInitConfig object to the new window.AliyunTimelinePlayer() constructor to initialize the player.

      interface PlayerInitConfig {
        licenseConfig?: {
          rootDomain?: string;
          licenseKey?: string;
        }; // License configuration
        getTimelineMaterials?: (params: TimelineMaterial[]) => Promise<InputMedia[]>; // timeline media material
        mode?: 'component' | 'player'; // Player component style: component to pure component
        componentClass?: string;
        container: Element;// Preview component's container, HTML element
        locale?: Locales;// Interface language, optional 'zh-CN' | 'en-US', default 'zh-CN'
        controls?: boolean; // Whether to display the broadcast control bar at the bottom, default true
        timeline?: AliyunTimeline; // The timeline object generated by the WebSDK is not completely consistent with the OpenAPI timeline.
        playbackRate?: number;// Playback speed during initialization, default is 1. Note that the range of this value is related to the browser's own playbackRate restrictions on video
        aspectRatio?: string;// Screen ratio at the time of initialization, the default is '16:9 '. The aspect ratio can be customized and connected by a colon. It is recommended to be consistent with the picture scale when making the AliyunTimeline.
        minWidth?: number | string;// Specifies the minimum width of the player
        customFontList?: CustomFontItem[]; // Custom Font List
        getMediaInfo?: (
          mediaId: string,
          mediaType: MediaType,
          mediaOrigin?: MediaOrigin | undefined,
          inputUrl?: string | undefined,
        ) => Promise<string | DynamicSrcObj>;
      }// Return the playback URL with authentication through the mediaId
    • The AliyunTimelinePlayer class definition:

      class AliyunTimelinePlayer {
        static getSubtitleEffectColorStyles(): Array<{
          key: string;
          cover: string;
        }>; // Gets the list of available word art effects.
        static getSubtitleBubbles(): Array<{
          key: string;
          cover: string;
        }>;// Gets the list of available bubble effects.
        static setDefaultLocale(locale?: Locales): void; // Sets the default language.
        static getDefaultFontList(): CustomFontItem[]; // Gets the default font list.
        static getVideoEffects(): Array<{
          subType: string;
          cover: string;
          name: string;
          title: string;
          category: string | undefined;
        }>; // Gets the list of available special effects.
        static getVideoFilters(): Array<{
          subType: string;
          cover: string;
          name: string;
          title: string;
          category: string | undefined;
        }>;// Gets the list of available filters.
        static getVideoTransitions(): Array<{
          subType: string;
          cover: string;
          name: string;
          title: string;
          category: string | undefined;
        }>;// Gets the list of available transitions.
        static parseTimeline(
          timeline: string | IServerTimeline,
          // You need to pass the size of the canvas. Generally, this corresponds to the Width and Height values of FECanvas in the timeline.
          options: { outputWidth: number; outputHeight: number } = { outputWidth: 800, outputHeight: 450 },
        ):ParsedResult; // Parses a backend timeline for frontend preview.
          constructor(config: PlayerInitConfig);
          play(): void; // Starts playback.
          pause(): void;  // Pauses playback.
          destroy(): void;  // Destroys the player instance.
          on(eventName: string, callback: Function): any; // Listens for an event. 
          once(eventName: string, callback: Function): any; // Listens for an event only once.
          off(eventName: string): any; // Removes an event listener.
          get event$(): IObservable<EventData<any>>; // The event stream that allows subscribing to all events. This follows RxJS subscription logic.
          get version(): string | undefined; // The SDK version.
          get duration(): number;// The total duration.
          get timeline(): any;// Gets the current timeline object.
          set timeline(timeline: any); // Sets the current timeline object.
          // (For SDK v5.2.2+) The current width of the stage. Used to calculate absolute x and y coordinates.
          get stageWidth(): number; 
          // (For SDK v5.2.2+) The current height of the stage. Used to calculate absolute x and y coordinates.
          get stageHeight(): number; 
          // (For SDK v5.2.2+) Set the timeline and automatically parse it.
          setTimeline(timeline: any, autoParse?: boolean): Promise<void>;
          get currentTime(): number;// Gets the current playback time.
          set currentTime(currentTime: number); // Sets the current playback time.
          get controls(): boolean; // Gets the display state of the controls.
          set controls(show: boolean); // Sets the display state of the controls.
          get aspectRatio(): string; // Gets the current aspect ratio.
          set aspectRatio(ratio: string); // Sets the current aspect ratio, for example, '16:9'.
          get playbackRate(): number; // Gets the playback rate.
          set playbackRate(speed: number); // Sets the playback rate.
          setFontList(value: CustomFontItem[]): Promise<void>; // Sets the list of custom fonts.
          // (For SDK v5.2.2+) Watch for track data changes.
          watchTrack(handler?: (tracks: ExportTrack[]) => void): () => void;
         // (For SDK v5.2.2+) Remove a track.
          removeTrack(id: number): void; 
         // (For SDK v5.2.2+) Set track properties.
          setTrack(id: number, options: {
              visible?: boolean;
              mainTrack?: boolean;
          }): void;
         // (For SDK v5.2.2+) Add a new track.
          addTrack(track: {id: number;type: TrackType; clips: ExportClip[];visible: boolean;mainTrack?: boolean;} ): void; 
         // (For SDK v5.2.2+) Remove a clip from a track.
         removeClip(id: number): void;
         // (For SDK v5.2.2+) Get the detailed configuration of a clip.
         getClip(id: number): ServerClip;
         // (For SDK v5.2.2+) Add a new clip to a track.
         addClip(clip: ServerClip): void;
         // (For SDK v5.2.2+) Set the in point of a clip.
         setClipTimelineIn(id: number, timelineIn: number): void;
         // (For SDK v5.2.2+) Set the out point of a clip.
         setClipTimelineOut(id: number, timelineOut: number): void;
         // (For SDK v5.2.2+) Update a clip.
         updateClip(id: number, handle: (clip: ServerClip) => ServerClip): void;
         // (For SDK v5.2.2+) Watch for changes to a clip.
         watchClip(id: number, handle: (clip: ServerClip | null) => void): () => void;
         // (For SDK v5.2.2+) Convert to a backend timeline object.
         toBackendTimeline(): {
              duration: number;
              timeline: any;
          };
         // (For SDK v5.2.2+) Query information about the current tracks.
         queryTracks(handler: (track: ExportTrack) => boolean): ExportTrack[];
         // (For SDK v5.2.2+) Query information about the current clips.
         queryClips(handler: (clip: ExportClip, track: ExportTrack) => boolean): ExportClip[];
         // (For SDK v5.2.2+) Focus a clip, allowing it to be moved freely.
         focusClip(id: number, autoSeek?: boolean): void;
         // (For SDK v5.2.2+) Blur the focused clip.
         blurClip(): void;
      }
      // A clip object exported by watchTrack. You can use getClip to retrieve its detailed properties.
      interface ExportClip {
        id: number;
        type: MaterialType;
        timelineIn: number;
        timelineOut: number;
      }
      // A track object exported by watchTrack.
      interface ExportTrack {
        id: number;
        type: TrackType;
        clips: ExportClip[];
        visible: boolean;
        mainTrack?: boolean;
      }
      // Custom font interface.
       interface CustomFontItem {
        key: string; // The unique key for the font.
        name?: string; // The display name.
        url: string; // The URL of the font file.
          urlType?: 'dynamic' | 'static'; // If the URL needs to be fetched dynamically from getMediaInfo, set this to 'dynamic'. Otherwise, set it to 'static'.
      }
      // Player state.
      enum PLAYER_STATE {
          PLAYING = 0,
          PAUSED = 1,
          STALLED = 2,
          ENDED = 3,
          BROKEN = 4
      }
      // Result of parsing a timeline on the frontend.
       interface ParsedResult {
        success: boolean; // Indicates whether parsing was successful.
        logs: any[];
        timeline: IServerTimeline; // The parsed timeline object.
        toBackendTimeline: (fTimeline: IServerTimeline) => IServerTimeline; // A function to convert a frontend timeline to a backend timeline.
        mediaMap: ParsedMediaMap;
        output: {
          width: number;
          height: number;
        };
        fontList: Array<{ key: string; url: string }>;
      }
      type ParsedMediaMap = {
        [key: string]: {
          mediaType: string;
          mediaId: string;
          mediaUrl?: string;
          width?: number;
          height?: number;
          duration: number;
        };
      }
       type InputMedia = (InputVideo | InputAudio | InputImage);
       interface InputVideo {
        mediaId: string;
        mediaIdType?: MediaIdType;
        mediaType: 'video';
        video: {
          duration: number;
        };
      }
       interface InputAudio   {
        mediaId: string;
        mediaIdType?: MediaIdType;
        mediaType: 'audio';
        audio: {
          duration: number;
        };
      }
       interface InputImage   {
        mediaId: string;
        mediaIdType?: MediaIdType;
        mediaType: 'image';
        image: {
          coverUrl?: string;
        };
      }
      type MediaIdType = 'mediaId' | 'mediaURL';
  3. Destroy the instance.

    Call the destroy method to release the player instance and empty the container element.

    player.destroy();

Sample code

Complete example of a preview player with custom fonts, transitions, special effects, and editable subtitles.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/vite.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link
      rel="stylesheet"
      href="https://g.alicdn.com/thor-server/video-editing-websdk/5.2.2/player.css"
    />
    <script src="https://g.alicdn.com/thor-server/video-editing-websdk/5.2.2/player.js"></script>
    <title>Online editing preview player</title>
  </head>

  <body>
    <div id="root" style="width: 820px;margin: 30px auto;" >
      <div id="player" style="width: 800px; height: 450px"></div>
      <div style="margin-top: 16px">
        <div>
          <label>ID</label>   <br/>
          <input id="subtitle" value="123" />
          <br/>
          <label>Content</label>   <br/>
          <textarea id="content"  rows="4" >Custom editable subtitle</textarea>
        </div>

        <button id="addSubtitle">Add subtitle</button>
        <button id="updateSubtitle">Modify subtitle</button>
        <button id="moveSubtitle">Move subtitle</button>
        <button id="removeSubtitle">Delete subtitle</button>
      </div>
    </div>
    <script type="text/javascript">
      const timelineDemo = {
        Version: 1,
        SdkVersion: "4.12.2",
        VideoTracks: [
          {
            // Video track.
            Id: 1,
            Type: "Video",
            Visible: true,
            Disabled: false,
            Count: 1,
            VideoTrackClips: [
              {
                // Image.
                Id: 3,
                TrackId: 1,
                Type: "Image",
                MediaURL:
                  "https://img.alicdn.com/imgextra/i4/O1CN01TDN7Gw1SCgVv61T4s_!!6000000002211-0-tps-1920-1046.jpg",
                Title: "test.png",
                X: 0,
                Y: 0,
                Width: 1,
                Height: 1,
                TimelineIn: 0,
                TimelineOut: 5,
                Duration: 5,
                VirginDuration: 5,
              },
              {
                // Video.
                Id: 4,
                TrackId: 1,
                Type: "Video",
                MediaURL:
                  "https://ice-pub-media.myalicdn.com/vod-demo/The.Most.Beautiful.China.Intelligent.Subtitle.mp4",
                X: 0,
                Y: 0,
                Width: 1,
                Height: 1,
                TimelineIn: 4, // The in point (TimelineIn) of the transition must be before the out point (TimelineOut) of the preceding clip.
                TimelineOut: 9,
                Duration: 5,
                VirginDuration: 5,
                Effects: [
                  {
                    // Transition.
                    Type: "Transition",
                    Id: 13,
                    Name: "transitions.directional",
                    SubType: "directional",
                    Duration: 1, // Transition duration = out point of the preceding clip (TimelineOut) - in point of this clip (TimelineIn).
                    From: 3, // ID of the preceding clip.
                  },
                ],
              },
            ],
          },
          {
            // Special effect track.
            Id: 2,
            Type: "Effect",
            Visible: true,
            Disabled: false,
            Count: 1,
            VideoTrackClips: [
              {
                Type: "VFX",
                Id: 2,
                TrackId: 1,
                SubType: "heartfireworks",
                TimelineIn: 0,
                TimelineOut: 5,
                Duration: 5,
                X: 0,
                Y: 0,
                Width: 0,
                Height: 0,
              },
            ],
          },
        ],
        AudioTracks: [],
        SubtitleTracks: [
          {
            Id: 2,
            Type: "Text",
            Visible: true,
            Disabled: false,
            Count: 1,
            SubtitleTrackClips: [
              {
                Id: 1,
                TrackId: 2,
                Type: "Text",
                X: 0,
                Y: 0,
                TimelineIn: 0,
                TimelineOut: 2,
                Duration: 2,
                VirginDuration: 2,
                FontSize: 30,
                FontColor: "#333333",
                FontColorOpacity: 1,
                Content: "Text with a custom font via FontUrl",
                Alignment: "BottomCenter",
                // Custom font.
                FontUrl:
                  "https://ice-pub-media.myalicdn.com/mts-fonts/ZhanKuWenYiTi.ttf",
              },
            ],
          },
        ],
        AspectRatio: "16:9",
        From: "websdk",
        FECanvas: {
          Width: 800,
          Height: 450,
        },
        FEConfig: {
          AutoProportion: "681:383",
        },
      };

      const player = new window.AliyunTimelinePlayer({
        container: document.getElementById("player"),
        getMediaInfo: async (mediaId, mediaType, mediaOri) => {
          console.log(">>>", mediaId, mediaType, mediaOri);
          // If the timeline uses a public mediaUrl, you can return the URL directly.
          return mediaId;
          /**
           * // For dynamic URL requests, refer to the following code:
           *     if (mediaType === "font") {
        params.InputURL = InputURL;
        delete params.MediaId;
      }
      if (mediaOrigin === "mediaURL") {
        params.InputURL = mediaId;
        delete params.MediaId;
      }

      const apiName =
        mediaOrigin === "public" ? "GetPublicMediaInfo" : "GetMediaInfo";
      return request(apiName, {
        MediaId: mediaId,
      })
        .then((res) => {
          // Note: This is only an example. In a production environment, you should implement proper error handling, for example, to prevent errors when FileInfoList is an empty array.
          const fileInfoList = get(res, "data.MediaInfo.FileInfoList", []);
          let mediaUrl, maskUrl;
          let sourceFile = fileInfoList.find((item) => {
            return item?.FileBasicInfo?.FileType === "source_file";
          });
          if (!sourceFile) {
            sourceFile = fileInfoList[0];
          }
          const maskFile = fileInfoList.find((item) => {
            return (
              item.FileBasicInfo &&
              item.FileBasicInfo.FileUrl &&
              item.FileBasicInfo.FileUrl.indexOf("_mask") > 0
            );
          });
          if (maskFile) {
            maskUrl = get(maskFile, "FileBasicInfo.FileUrl");
          }
          mediaUrl = get(sourceFile, "FileBasicInfo.FileUrl");
          const codec = get(sourceFile, "VideoStreamInfoList[0].CodecName");

          return {
            url: mediaUrl,
            codec,
            maskUrl,
          };
        })
        .catch((ex) => {
          // Fallback logic for external URLs.
          if (mediaOrigin === "mediaURL") {
            return mediaId;
          }
        });
           *
           * **/
        },
      });

      // Preview the frontend timeline. The setTimeline method automatically parses MediaUrl and font files.
      player.setTimeline(timelineDemo);
      // You can convert it to a backend timeline by using toBackendTimeline.
      console.log("toBackendTimeline", player.toBackendTimeline());

      document.getElementById("addSubtitle").addEventListener("click", () => {
        player.addClip({
          Id: Number(document.getElementById('subtitle').value),
          TrackId: 2,
          Type: "Text",
          X: 0,
          Y: 0,
          TimelineIn: player.currentTime,
          TimelineOut: player.currentTime+2,
          Duration: 2,
          VirginDuration: 2,
          FontSize: 30,
          FontColor: "#333333",
          FontColorOpacity: 1,
          Content: document.getElementById('content').value,
          Alignment: "TopCenter",
          // Custom font.
          FontUrl:
            "https://ice-pub-media.myalicdn.com/mts-fonts/ZhanKuWenYiTi.ttf",
        });
      });
      document.getElementById("updateSubtitle").addEventListener("click", () => {
        player.updateClip(Number(document.getElementById('subtitle').value),(item)=>{
          return Object.assign({},item,{Content: document.getElementById('content').value})
        });
      });
      document.getElementById("moveSubtitle").addEventListener("click", () => {
        player.focusClip( Number(document.getElementById('subtitle').value));
      });
      document.getElementById("removeSubtitle").addEventListener("click", () => {
        player.blurClip();
        player.removeClip( Number(document.getElementById('subtitle').value));
      });
      // Watch for track changes.
      player.watchTrack((tracks)=>{
         console.log('Timeline changed:');
         console.log(JSON.stringify(tracks,null,4));
      });
    </script>
  </body>
</html>

For advanced use cases such as editing tracks, subtitles, special effects, transitions, positions, dimensions, and customizing the player UI, use the open-source demo. Try the Demo.

image

FAQ

How do I update the timeline?

After creating an AliyunTimelinePlayer instance, update the timeline by direct assignment.

player.timeline = {....}

If caching causes issues, assign an empty object to clear the timeline before setting the new one.

player.timeline = {} // Assign an empty object to clear the timeline content.

Mismatched font size in preview and video

If the font appears smaller after composition, ensure the timeline object includes the FECanvas field, which specifies the preview resolution. The backend scales fonts based on this resolution and the output resolution. Common FECanvas values:

//16:9
FECanvas: {Width: 800, Height: 450}
//9:16
FECanvas: {Width: 253.125, Height: 450}

List of built-in materials

// Get the font list.
AliyunTimelinePlayer.getDefaultFontList();
// Get the list of word art effects.
AliyunTimelinePlayer.getSubtitleEffectColorStyles(); 
// Get the list of bubble effects.
AliyunTimelinePlayer.getSubtitleBubbles();
// Get the list of special effects.
AliyunTimelinePlayer.getVideoEffects(); 
// Get the list of filters.
AliyunTimelinePlayer.getVideoFilters();
// Get the list of transitions.
AliyunTimelinePlayer.getVideoTransitions();
Important

Retain the space in the parameter value, for example: "Font":"Alibaba PuHuiTi",.

Multiple instance support

No. The preview player supports only a single instance.

Frontend error: Cannot read properties of undefined (reading 'GLctx')

This error typically occurs when hardware acceleration is disabled. Use a Chrome-based browser (version 80 or later) with hardware acceleration enabled.

Note

The video editing Web SDK supports only Chrome-based browsers.

Text not displaying in preview

Serve the page over HTTP, such as http://localhost:8080. Do not open it as a local file with the file:// protocol.

References

FAQ