This topic provides sample code for you to implement frequently used features of ApsaraVideo Player SDK for Windows.

Basic features

Create a player

This section describes how to play videos by using ApsaraVideo Player SDK for Windows with ease. You can create a player for manual playback or autoplay.

  1. Create a player.
    Create an AliPlayer object.
    using namespace alivc_player;
    AliPlayer* mPlayerPtr = AliPlayer::CreatePlayer();
  2. Configure listeners.
    ApsaraVideo Player SDK for Windows provides multiple callbacks, such as onPlayerEvent and onError. To use these callbacks, create a class to inherit IAVPListener and implement the pure virtual functions of the class. The following sample code provides an example:
    mPlayerPtr->setListener(new AVPListenerImpl);
  3. Set a playback source.
    • ApsaraVideo Player SDK for Windows supports four types of playback sources for video-on-demand (VOD) playback: UrlSource, VidAuth, VidSts, and VidMps. We recommend that you use VidAuth sources in ApsaraVideo VOD.
    • ApsaraVideo Player SDK for Windows supports only UrlSource sources for live stream playback.

    VOD playback

    To use UrlSource for URL-based playback, you must set the source parameter to the streaming URL. You can specify the streaming URL of an audio or video file stored in a third-party VOD service or in ApsaraVideo VOD. You can call the GetPlayInfo operation to obtain the streaming URL of an audio or video file stored in ApsaraVideo VOD. We recommend that you integrate an ApsaraVideo VOD server operation SDK to obtain the streaming URL of an audio or video file stored in ApsaraVideo VOD. This frees you from complex signature calculations. For more information about how to call the GetPlayInfo operation, see OpenAPI Explorer.

    Demo of UrlSource

    AVPUrlSource urlSource;
    urlSource.setUrl("Streaming URL");  // The streaming URL of an audio or video file stored in a third-party VOD service or in ApsaraVideo VOD. 
    mPlayerPtr->setSource(urlSource);

    To use VidAuth for VOD playback, you must set the Vid parameter to the audio or video ID and set the playAuth parameter to the playback credential. After you upload an audio or video file, you can log on to the ApsaraVideo VOD console and choose Media Files > Audio/Video to view the audio or video ID. You can also call the SearchMedia operation by using the server operation SDK to obtain the audio or video ID. For more information, see SearchMedia. You can call the GetVideoPlayAuth operation to obtain the playback credential. We recommend that you integrate an ApsaraVideo VOD server operation SDK to obtain the playback credential. This frees you from complex signature calculations. For more information about how to call the GetVideoPlayAuth operation, see OpenAPI Explorer.

    We recommend that you use VidAuth for playback in ApsaraVideo VOD. Compared with Security Token Service (STS)-based playback, playback implemented based on playback credentials is easier to use and more secure. For more information about the comparison between the two playback methods, see Comparison between credentials and STS.

    Demo of VidAuth

    AVPVidAuthSource authSource;
    authSource.initWithVid("Audio or video ID",
        "Playback credential",  // The playback credential.
         "Access region ID");  // The ID of the region from which you want to access ApsaraVideo VOD. Default value: cn-shanghai.
    mPlayerPtr->setSource(authSource);

    If you use VidSts sources, a temporary STS token rather than a playback credential is used. You must obtain the temporary STS token in advance. For more information, see Create a role and grant temporary access permissions to the role by using STS. You must set the SecurityToken parameter to the obtained STS token and set the AccessKeyId and AccessKeySecret parameters to the AccessKey ID and AccessKey secret that are generated based on the STS token.

    Demo of VidSts

    AVPVidStsSource vidSource;
    vidSource.initWithVid("Video ID",   // The video ID.
    "<yourAccessKeyId>",   // The AccessKey ID used for authentication.
    "<yourAccessKeySecret>",  // The AccessKey secret used for authentication.
     	"<yourSecurityToken>",   // The security token.
    "Access region ID",   // The ID of the region from which you want to access ApsaraVideo VOD.
    nullptr);
    mPlayerPtr->setSource(vidSource);

    You can use VidMps for playback if you use the ApsaraVideo Media Processing (MPS) service. You must obtain the following information in advance:

    • Vid: the ID of the media asset in MPS.
    • AcessKeyId and AccessKeySecret: the AccessKey pair that is issued together with the temporary STS token.
    • SecurityToken: the temporary STS token.
    • domainRegion: the region in which the media asset resides.
    • authInfo: the authorization information.

    For information about media assets in MPS, see Play videos.

    Demo of VidMps

    AVPVidMpsSource mpsSource;
    mpsSource.initWithVid("Media ID",   // The media ID, which also indicates the video ID. To obtain the video ID, log on to the MPS console and choose Media Management > Media List. On the page that appears, you can query the video ID. Example: 1e067a2831b641db90d570b6480f****. 
    "<yourAccessKeyId>", // The AccessKey ID used for authentication.
             "<yourAccessKeySecret>",  // The AccessKey secret used for authentication.
    "<yourSecurityToken>",   // The security token.
             "Authentication information", // The authentication information.
    "Access region ID", // The ID of the region in which the media asset resides, such as cn-shanghai or cn-hangzhou. 
    "Streaming domain", // The streaming domain.
             "HlsUriToken"); // The HlsUriToken of the media asset.
    mPlayerPtr->setSource(mpsSource);

    Live stream playback by using UrlSource sources

    To use UrlSource for URL-based playback, you must set the setUrl parameter to the source URL. You can specify the source URL of a live stream in a third-party live streaming service or in ApsaraVideo Live. The ApsaraVideo Live console provides a URL generator to help you generate source URLs. For more information, see URL generator.

    AVPUrlSource urlSource;
    urlSource.setUrl("Source URL");  // The source URL of a live stream in a third-party live streaming service or in ApsaraVideo Live. 
    mPlayerPtr->setSource(urlSource);
  4. Configure the UI view.
    If the playback source contains video images, you must configure the UI view to display the video images in the player. The following sample code provides an example:
    mPlayerPtr->setView((void *) The window handle (HWND) of the UI view);
  5. Prepare the player.
    Call the prepare() method to prepare the player.
    mPlayerPtr->prepare();
  6. Optional: Enable autoplay. By default, the autoplay feature is disabled.
    mPlayerPtr->setAutoPlay(true);
  7. Start the playback.
    • If the autoplay feature is disabled, you must call the mPlayerPtr->start(); method to start playback in the OnPrepard callback.
    • If the autoplay feature is enabled, you do not need to call the mPlayerPtr->start(); method. After the data is parsed, the video playback automatically starts.
    mPlayerPtr->start();

Control the playback

ApsaraVideo Player SDK for Windows provides methods to implement playback control features. The basic playback control features include play, pause, and playback from a specified position.

Start the playback

Start the playback by calling the start method. The following sample code provides an example:
mPlayerPtr->start();

Play the video from a specified position

Play the video from a specified position by calling the seekToTime method. This feature is applicable to scenarios in which you want to start playback from a specified position. For example, use this feature if you want to seek video content or resume the video playback from the paused position. The following sample code provides an example:
// Seek to a position at a specific point in time. 
// Valid values of the mode parameter: AVP_SEEKMODE_ACCURATE and AVP_SEEKMODE_INACCURATE. A value of AVP_SEEKMODE_ACCURATE indicates precise seek. A value of AVP_SEEKMODE_INACCURATE indicates imprecise seek. Imprecise seek navigates you to the nearest next keyframe of the video. Precise seek navigates you to the video image at the specified point in time, but takes longer time than imprecise seek. 
mPlayerPtr->seekToTime(int64_t time_in_ms, mode);

Pause the playback

Pause the playback by calling the pause method. The following sample code provides an example:
mPlayerPtr->pause();

Stop the playback

Stop the playback by calling the stop method. The following sample code provides an example:
mPlayerPtr->stop();

Set the video display mode.

ApsaraVideo Player SDK for Windows provides multiple methods for you to control video images. You can set the scaling mode, rotation angle, and mirroring mode for video images.

Set the scaling mode

Set the scaling mode to aspect ratio-based fitting, aspect ratio-based padding, or stretching by calling the setScalingMode method. The following sample code provides an example:
// Use aspect ratio-based fitting. The video image is scaled down into the UI view without changing the aspect ratio. This prevents image distortion.
mPlayerPtr->setScalingMode(AVP_SCALINGMODE_SCALEASPECTFIT);
// Use aspect ratio-based padding. The video image is scaled up to fill the UI view without changing the aspect ratio. This prevents image distortion.
mPlayerPtr->setScalingMode(AVP_SCALINGMODE_SCALEASPECTFILL);
// Use stretching. The video image is stretched to fill the UI view. This may cause image distortion if the video image and the UI view do not match in the aspect ratio.
mPlayerPtr->setScalingMode(AVP_SCALINGMODE_SCALETOFILL);

Set the rotation angle

Set the rotation angle for video images by calling the setRotateMode method. You can query the rotation angle after you complete the setting. The following sample code provides an example:
// Set the rotation angle to 0°, in the clockwise direction.
mPlayerPtr->setRotateMode(AVP_ROTATE_0);
// Set the rotation angle to 90°, in the clockwise direction.
mPlayerPtr->setRotateMode(AVP_ROTATE_90);
// Set the rotation angle to 180°, in the clockwise direction.
mPlayerPtr->setRotateMode(AVP_ROTATE_180);
// Set the rotation angle to 270°, in the clockwise direction.
mPlayerPtr->setRotateMode(AVP_ROTATE_270);
// Obtain the rotation angle.
mPlayerPtr->getRotateMode();

Set the mirroring mode

Set the mirroring mode to horizontal mirroring, vertical mirroring, or no mirroring by calling the setMirrorMode method. The following sample code provides an example:
// Disable mirroring.
mPlayerPtr->setMirrorMode(AVP_MIRRORMODE_NONE);
// Use horizontal mirroring.
mPlayerPtr->setMirrorMode(AVP_MIRRORMODE_HORIZONTAL);
// Use vertical mirroring.
mPlayerPtr->setMirrorMode(AVP_MIRRORMODE_VERTICAL);       

Obtain the playback information

ApsaraVideo Player SDK for Windows allows you to obtain the playback information, including the current playback position and total playback duration.

Obtain the current playback position

Obtain the current playback position after the onCurrentPositionUpdate callback is invoked. Unit: milliseconds. The following sample code provides an example:
void AlivcLivePlayerMainDlg::onCurrentPositionUpdate(AliPlayer *player, int64_t position)
{
    // The position parameter indicates the current playback position. Unit: milliseconds.
printf("current position is %lld ms", position);
}

Obtain the total playback duration

You can obtain the total duration of a video only after the video is loaded. The total duration of a video is returned in the duration parameter after the AVPEventPrepareDone event is triggered. The following sample code provides an example:
void AlivcLivePlayerMainDlg::onPlayerEvent(AliPlayer *player, AVPEventType eventType)
{
    if (eventType == AVPEventPrepareDone) {
        int64_t duration = mPlayerPtr->getDuration();
printf("total duration is %lld ms", duration);
    }
}

Obtain the loading progress

Obtain the current loading progress of the video after the onBufferedPositionUpdate callback is invoked. The following sample code provides an example:
void AlivcLivePlayerMainDlg::onBufferedPositionUpdate(AliPlayer *player, int64_t position)
{
    printf("buffered position is %lld ms", position);
}

Listen to the playback status

You can listen to the playback status. The parameters of the onPlayerStatusChanged callback indicate the playback status. The following sample code provides an example:
void AlivcLivePlayerMainDlg::onPlayerStatusChanged(AliPlayer *player, AVPStatus oldStatus, AVPStatus newStatus)
{
    switch (newStatus) {
case AVPStatusIdle:{
// The player is idle.
}
break;
case AVPStatusInitialzed:{
// The player is initialized.
}
 break;
     case AVPStatusPrepared:{
// The player is prepared.
}
break;
case AVPStatusStarted:{
// The player is playing a video.
}
 break;
case AVPStatusPaused:{
// The playback is paused.
}
break;
case AVPStatusStopped:{
// The playback is stopped.
 }
break;
case AVPStatusCompletion:{
// The playback is complete.
 }
break;
case AVPStatusError:{
// A playback error occurs.
 }
break;
default:
break;
}
}

Set the volume.

You can set the mute mode and the volume.

Set the volume

Set the volume by calling the setVolume method. You can also obtain the volume after you complete the setting. The following sample code provides an example:
// Specify the player volume. Valid values: 0 to 2.0. 
mPlayerPtr->setVolume(1.0f);
// Obtain the volume. 
mPlayerPtr->getVolume();

Mute the player

Mute the player by calling the setMute method. The following sample code provides an example:
mPlayerPtr->setMute(true);

Set the playback speed

ApsaraVideo Player SDK for Windows allows you to set the playback speed. You can call the setRate method to change the playback speed from 0.5× to 2×. The audio pitch remains unchanged at different speeds. The following sample code provides an example:
// Set the playback speed. You can set the playback speed from 0.5× to 2×. The value must be a multiple of 0.5, such as 0.5, 1, and 1.5.
mPlayerPtr->setRate(1.5);

Set multi-definition playback

If you use VidAuth or VidSts for playback, you do not need to manually set parameters for multi-definition playback. We recommend that you use VidAuth sources. ApsaraVideo Player SDK for Windows obtains the definitions supported by ApsaraVideo VOD. You can query and switch the video definition as needed. If you use UrlSource sources, you cannot set multi-definition playback.

Obtain the definitions

When the video is loaded, you can obtain the definitions of the video.
void AlivcLivePlayerMainDlg::onTrackReady(AliPlayer *player, AVPTrackInfo *info[], int count)
{
    if (count < 0) {
        return;
    }

    for (int i = 0; i < count; i++) {
        AVPTrackInfo *track = info[i];
        switch (track->trackType) {
            case AVPTRACK_TYPE_VIDEO: {
                int trackBitrate = track->trackBitrate;
            } break;
        }
    }
}

Switch the video definition

You can switch the video definition by calling the selectTrack method. Set the trackIndex parameter when you call the selectTrack method.
mPlayerPtr->selectTrack(trackIndex);

Set the callback for definition switching

Set the callback for definition switching.
void AlivcLivePlayerMainDlg::onTrackChanged(AliPlayer *player, AVPTrackInfo *info)
{
    // The definition is switched.
}

Enable loop playback

ApsaraVideo Player SDK for Windows supports loop playback. To configure the loop playback feature, call the setLoop method. The loop playback feature allows the player to play a video again when the player plays the video to the end position. A notification of the AVPEventLoopingStart event is returned to start the loop playback. The following sample code provides an example:
mPlayerPtr->setLoop(true);

Advanced features

Add external subtitles

ApsaraVideo Player SDK for Windows allows you to add and switch external subtitles. Only subtitle files in the .srt format are supported. The following sample code provides an example:

  1. Create a control for displaying subtitles.
    Create UI views based on subtitle files in different formats.
    mSubtitleLabelPtr = new QLabel(QString(""), this);
    mSubtitleLabelPtr->setParent(this);
  2. Configure listeners.
    // The external subtitles are added.
    void AlivcLivePlayerMainDlg::onSubtitleExtAdded(AliPlayer *player, int64_t trackIndex, const char *URL)
    {
        emit SgnAddExtSubtitle((qint64) trackIndex);
    }
    // The callback for displaying the subtitles.
    void AlivcLivePlayerMainDlg::onSubtitleShow(AliPlayer *player, int64_t trackIndex, int64_t subtitleId, const char *subtitle)
    {
        emit SgnUpdateSubtitle(QString::fromStdString(subtitle), true);
    }
    // The callback for hiding the subtitles.
    void AlivcLivePlayerMainDlg::onSubtitleHide(AliPlayer *player, int64_t trackIndex, int64_t subtitleId)
    {
        emit SgnUpdateSubtitle(QString(""), false);
    }
  3. Add subtitles.
    mPlayerPtr->addExtSubtitle("url");
  4. Switch subtitles.
    mPlayerPtr->selectExtSubtitle(trackIndex, true);

Perform audio-only playback

You can perform audio-only playback by disabling the playback of video streams. You must set the PlayerConfig class before you prepare the player.
AVPConfig *config = mPlayerPtr->getConfig();
config->mDisableVideo = true;
mPlayerPtr->setConfig(config);

Enable adaptive bitrate definition switching

ApsaraVideo Player SDK for Windows supports video streams that are packaged by using HTTP-Live-Streaming (HLS) or Dynamic Adaptive Streaming over HTTP (DASH). After the player is prepared by using the prepare method, you can call the getMediaInfo method to obtain the bitrate information, which is indicated by the TrackInfo parameter. The following sample code provides an example:
AVPMediaInfo info = mPlayerPtr->getMediaInfo();
for (int i = 0; i < info.trackCount; i++) {
     AVPTrackInfo *track = info.tracks[i];
}
Note HLS or DASH files are generated by using an adaptive bitrate streaming template group. To create a streaming template group, log on to the ApsaraVideo VOD console and choose Configuration Management > Media Processing > Transcoding Template Groups. On the page that appears, you can create a streaming template group based on your requirements. For more information, see Configure video packaging templates.
You can switch the bitrate by calling the selectTrack method during playback. A value of SELECT_AVPTRACK_TYPE_VIDEO_AUTO indicates adaptive bitrate streaming. The following sample code provides an example:
// Switch the bitrate.
mPlayerPtr->selectTrack(trackIndex);
// Switch to the adaptive bitrate.
mPlayerPtr->selectTrack(SELECT_AVPTRACK_TYPE_VIDEO_AUTO);
You can view the switching result after the onTrackChanged callback is invoked. The following sample code provides an example:
void AlivcLivePlayerMainDlg::onTrackChanged(AliPlayer *player, AVPTrackInfo *info)
{
    if (info->trackType == AVPTRACK_TYPE_VIDEO) {
        // video changed
    }
    // etc
}

Configure the snapshot capture feature

ApsaraVideo Player SDK for Windows provides the snapShot method for you to configure the snapshot capture feature. The player saves the captured snapshots in the ARGB32 format. You can obtain the information about the captured snapshots after the onSnapshotImageBuffer callback is invoked. The following sample code provides an example:
// Take a snapshot of the current video image.
mPlayerPtr->snapshot();
// Invoke a callback for snapshot capture.
void AlivcLivePlayerMainDlg::onSnapshotImageBuffer(AliPlayer *player, int width, int height, unsigned char *pARGBBuffer)
{
    QString savePath = "save path";
    QImage snapshot(pARGBBuffer, width, height, QImage::Format_ARGB32);
    snapshot.save(savePath);
}
Notice The snapshot is a video image that does not contain the UI.

Configure the preview feature

ApsaraVideo Player SDK for Windows allows you to configure the preview feature in ApsaraVideo VOD. This feature supports VidAuth and VidSts sources. We recommend that you use VidAuth for playback. For more information about how to configure and use the preview feature, see Configure the preview feature.

After you enable the preview feature, you can call the setPreviewTime method in VidPlayerConfigGenerator to specify the preview duration. After you specify the preview duration, ApsaraVideo Player SDK allows you to preview a video for the specified duration instead of the whole video. In this example, VidSts is used for playback. The following sample code provides an example:
VidPlayerConfigGenerator playConfigGen;
playConfigGen.setPreviewTime(10);
AVPVidStsSource vidSource;
vidSource.initWithVid(Video ID,
                        "accessKeyId",
                        "accessKeySecret",
                        "Security token",
                        "Access region ID",
                        playConfigGen.generatePlayerConfig());
mPlayerPtr->setSource(vidSource);

Set the referer

ApsaraVideo Player SDK for Windows provides the AVPConfig class for you to set the request referer. You can implement access control by setting referers in the blacklist or whitelist in the ApsaraVideo VOD console. The following sample code provides an example:
// Obtain the configuration information.
AVPConfig *pConfig = mPlayerPtr->getConfig();
// Set the referer.
pConfig->referer = referer;
....// Configure other settings.
// Configure the settings for the player.
mPlayerPtr->setConfig(pConfig);

Specify the user agent

ApsaraVideo Player SDK for Windows provides the AVPConfig class for you to specify the user agent. After you specify the user agent, the player contains the user agent information in its requests. The following sample code provides an example:
// Obtain the configuration information.
AVPConfig *pConfig = mPlayerPtr->getConfig();
// Specify the user agent.
pConfig->userAgent = userAgent;
....// Configure other settings.
// Configure the settings for the player.
mPlayerPtr->setConfig(pConfig);

Set the network timeout period and number of retries

ApsaraVideo Player SDK for Windows provides the AVPConfig class for you to set the network timeout period and number of retries. The following sample code provides an example:
// Obtain the configuration information.
AVPConfig *pConfig = mPlayerPtr->getConfig();
// Specify the network timeout period. Unit: milliseconds.
pConfig->networkTimeout = 5000;
// Specify the number of retries upon a network timeout. The retry interval equals the value of the networkTimeout parameter. The networkRetryCount parameter specifies the number of retries. A value of 0 indicates no retry. The application determines the number of retries. Default value: 2.
pConfig->networkRetryCount = 2;
....// Configure other settings.
// Configure the settings for the player.
mPlayerPtr->setConfig(pConfig);
Note
  • If you set the networkRetryCount parameter to a value other than 0, the player retries playback when the player starts to load data due to a network error. The number of retries equals the value of the networkRetryCount parameter. The retry interval equals the value of the networkTimeout parameter.
  • If the player is still loading data after the maximum number of retries, the onError callback is invoked. In this case, the ERROR_LOADING_TIMEOUT error is returned in the code parameter of the AVPErrorModel class.
  • If you set the networkRetryCount parameter to 0, the onPlayerEvent callback is invoked when the network connection times out. The value of the eventWithString parameter is EVENT_PLAYER_NETWORK_RETRY. To resolve this issue, call the reload method to reload data or perform other operations as required.

Control the buffer and latency

Buffer control is important for a player. You can significantly shorten the startup loading time and improve playback smoothness with proper configuration. ApsaraVideo Player SDK for Windows provides the AVPConfig class for you to configure the buffer and latency. The following sample code provides an example:
// Obtain the configuration information.
AVPConfig *pConfig = mPlayerPtr->getConfig();
// Set the maximum latency. This parameter is valid only for live streaming. If the latency exceeds the maximum limit, ApsaraVideo Player SDK synchronizes frames to ensure that the latency is within the limit. 
pConfig->maxDelayTime = 5000;
// Set the maximum buffer duration. Unit: milliseconds. This parameter specifies the maximum buffer duration for the player to load data at a time. 
pConfig->maxBufferDuration = 50000;
// Set the peak buffer duration. Unit: milliseconds. The player starts to load data if the network condition is unstable. This parameter specifies the buffer duration beyond which the player stops loading data in this case. 
pConfig->highBufferDuration = 3000;
// Set the startup loading duration. Unit: milliseconds. A smaller value indicates a shorter startup loading time. In this case, the player starts to load data sooner after the start of playback. 
pConfig->startBufferDuration = 500;
// Configure other settings.
// Configure the settings for the player.
mPlayerPtr->setConfig(pConfig);
Notice Make sure that the value of the startBufferDuration parameter is not greater than the value of the highBufferDuration parameter. Make sure that the value of the highBufferDuration parameter is not greater than the value of the maxBufferDuration parameter.

Configure HTTP headers

ApsaraVideo Player SDK provides the AVPConfig class for you to configure HTTP headers for the player. The following sample code provides an example:
// Obtain the configuration information.
AVPConfig *pConfig = mPlayerPtr->getConfig();
// Configure the headers.
pConfig->headerCount = 1;
pConfig->httpHeaders = new char *[pConfig->headerCount];
// Configure a host when you use Alibaba Cloud HTTPDNS. 
pConfig->httpHeaders[0] = strdup("Host:example.com");
....// Configure other settings.
// Configure the settings for the player.
mPlayerPtr->setConfig(pConfig);

Feature for performance optimization

Configure the local caching feature

ApsaraVideo Player SDK for Windows allows you to cache videos during playback. This saves your traffic during loop playback. To configure the play-and-cache feature, call the AVPCacheConfig method before you call the prepare method. The following sample code provides an example:
AVPCacheConfig mCacheConfig;
// Enable the play-and-cache feature.
mCacheConfig.enable = true;
// Specify the maximum duration of a single cached file. Files whose duration exceeds the maximum limit are not cached.
mCacheConfig.maxDuration = 100;
// Specify the maximum size of the cache directory. When the total size of cached files in the cache directory exceeds the maximum limit, the earliest cached files are overwritten.
mCacheConfig.maxSizeMB = 200;
// Specify the cache directory. Specify it as required by your application.
mCacheConfig.path = strdup("please use your cache path here");
// Configure the cache settings for the player.
mPlayerPtr->setCacheConfig(&mCacheConfig);
You can use cached files only after you call the setCacheConfig method. The cached files are used in the following scenarios:
  • If the loop playback feature is enabled, the cached files are used when the player replays the video.
  • After you cache a video and create a player to play the video, the new player plays the video by using the cached video file.
    Notice The player uses information such as the video ID from online requests to find cached files for video ID-based playback.
The following information describes the limits on the play-and-cache feature:
  • If the player plays UrlSource streams by using the HLS protocol based on the URL in an M3U8 playlist, the player does not cache the video during the playback. For other supported formats, the player caches videos during playback as configured.
  • If you use VidAuth or VidSts sources for playback, the player caches videos during playback as configured.
  • A video is cached when the player reads all video data. Caching fails if the stop method is called or the onError callback is invoked before the player reads all video data.
  • Seeking to a position inside the cached video does not affect the caching result. Seeking to a position outside the cached video may cause a caching failure.
  • If the security file does not match the application information, the video caching may fail.
  • You can check whether the caching result is EVENT_PLAYER_CACHE_SUCCESS or EVENT_PLAYER_CACHE_ERROR after the onPlayerEvent callback is invoked.

Video download

ApsaraVideo Player SDK for Windows allows you to download videos from ApsaraVideo VOD by using VidAuth or VidSts. ApsaraVideo VOD supports the secure download mode and the normal download mode. To configure the download settings, log on to the ApsaraVideo VOD console and choose Configuration Management > CDN Configuration > Download. On the page that appears, you can configure the download settings.
  • When you select the normal download mode, downloaded videos are not encrypted by Alibaba Cloud, even though the videos have been encrypted by ApsaraVideo VOD. In this case, you can use third-party players to play the downloaded videos.
  • When you select the secure download mode, downloaded videos are encrypted by Alibaba Cloud, even though the videos have not been encrypted by ApsaraVideo VOD. In this case, you cannot use third-party players to play the downloaded videos. You must use ApsaraVideo Player to play the downloaded videos.
  1. Create a download object. The following sample code provides an example:
    mMediaDownloader = AliMediaDownloader::CreateMediaDownloader();
    mMediaDownloader->setListener(new AVDListenerImpl);
    mMediaDownloader->setSaveDirectory("saveDir");
    ApsaraVideo Player SDK for Windows allows you to download videos that are encrypted by using Alibaba Cloud proprietary cryptography. To ensure security, configure a security file encryptedApp.dat for encryption verification. The following sample code provides an example:
    InitPrivateService(fileContentBuffer, fileLength);
  2. Prepare the download source.
    You can call the prepare method to prepare a download source. VidSts and VidAuth are supported as download sources. We recommend that you use VidAuth sources. In the following example, VidSts is used.
    AVPVidStsSource vidSource;
    vidSource.initWithVid(Video ID,
                            "accessKeyId",
                            "accessKeySecret",
                            "Security token",
                            "Access region ID",
                            nullptr);
    mMediaDownloader->prepareWithVid(&vidSource);
  3. Select the content to be downloaded from the prepared download source.
    After the download source is prepared, the onPrepared callback is invoked. Select a track for download. The following sample code provides an example:
    void YourClass::onPrepared(AliMediaDownloader *downloader, AVPMediaInfo *mediaInfo) {
        AVPTrackInfo *track = mediaInfo->tracks[0];
        mMediaDownloader->selectTrack(track->trackIndex);
    }
  4. Update the download source and start the download.
    After the preceding steps, start the download. We recommend that you update the download source information to ensure that the VidSts or VidAuth source is valid. The following sample code provides an example:
    mMediaDownloader->updateWithVid(&vidSource);
    mMediaDownloader->start();
  5. Release the download object after the download succeeds or fails.
    After the download succeeds, release the download object. The following sample code provides an example:
    delete mMediaDownloader;
    mMediaDownloader = nullptr;

References

API operations