All Products
Search
Document Center

Features and usage

Last Updated: Sep 17, 2019

ApsaraVideo Player SDK for iOS provides the following features:

  • Playing a single video
  • Playing videos in a list
  • Download
  • Caching

This topic describes these features.

1. Playback

The playback procedure is as follows:

  1. Create a player. 2. Set listeners. 3. Set the playback source. 4. Prepare the player. 5. Start playback. 6. Set operations for playback control. 7. Release the player.

1. Create a player

You can create either of the two player objects: AliPlayer or AliListPlayer.
AliListPlayer and AliPlayer provide almost the same features, except that AliListPlayer provides a feature of list playback. The sample code is as follows:

  1. self.player = [[AliPlayer alloc] init];
  2. self.listPlayer = [[AliListPlayer alloc] init];

To play a video that is downloaded securely, that is, a video that is encrypted and transcoded by Alibaba Cloud, you need to configure a security file for encryption verification. We recommend that you configure the security file in your application, and you only need to do that once.

  1. NSString *encrptyFilePath = [[NSBundle mainBundle] pathForResource:@"encryptedApp" ofType:@"dat"];
  2. [AliPrivateService initKey:encrptyFilePath];

The following error message is returned if you do not properly configure a security file: ERROR_DEMUXER_OPENSTREAM.

2. Set a player delegate

ApsaraVideo Player SDK for iOS provides multiple delegate methods, such as onPlayerEvent and onError. The sample code is as follows:

  1. @interface SimplePlayerViewController ()<AVPDelegate>
  2. @end
  3. - (void)viewDidLoad {
  4. self.player = [[AliPlayer alloc] init];
  5. self.player.playerView = self.avpPlayerView.playerView;
  6. self.player.delegate = self;
  7. //...
  8. }
  9. /**
  10. @brief The callback for an incorrect delegate.
  11. @param player The method pointer for the player.
  12. @param errorModel The description of player errors. This parameter is similar to the AliVcPlayerErrorModel parameter.
  13. */
  14. - (void)onError:(AliPlayer*)player errorModel:(AVPErrorModel *)errorModel {
  15. // Indicate that an error occurs and the playback stops.
  16. }
  17. /**
  18. @brief The callback for player events.
  19. @param player The method pointer for the player.
  20. @param eventType The player event type. This parameter is similar to the AVPEventType parameter.
  21. */
  22. -(void)onPlayerEvent:(AliPlayer*)player eventType:(AVPEventType)eventType {
  23. switch (eventType) {
  24. case AVPEventPrepareDone: {
  25. // Triggered when preparation is complete.
  26. }
  27. break;
  28. case AVPEventAutoPlayStart:
  29. // The listener for the start of autoplay.
  30. break;
  31. case AVPEventFirstRenderedStart:
  32. // Triggered when the image of the first video frame is displayed.
  33. break;
  34. case AVPEventCompletion:
  35. // The listener for the completion of playback.
  36. break;
  37. case AVPEventLoadingStart:
  38. // Indicate that the player starts to buffer a video.
  39. break;
  40. case AVPEventLoadingEnd:
  41. // Indicate that the video buffering is complete.
  42. break;
  43. case AVPEventSeekEnd:
  44. // The listener for the completion of seeking.
  45. break;
  46. case AVPEventLoopingStart:
  47. // Triggered when the player starts loop playback.
  48. break;
  49. default:
  50. break;
  51. }
  52. }
  53. /**
  54. @brief The callback for the current playback position.
  55. @param player The method pointer for the player.
  56. @param position The current playback position.
  57. */
  58. - (void)onCurrentPositionUpdate:(AliPlayer*)player position:(int64_t)position {
  59. // Update the progress bar.
  60. }
  61. /**
  62. @brief The callback for the buffer position.
  63. @param player The method pointer for the player.
  64. @param position The current buffer position.
  65. */
  66. - (void)onBufferedPositionUpdate:(AliPlayer*)player position:(int64_t)position {
  67. // Update the buffer progress.
  68. }
  69. /**
  70. @brief The callback for obtaining the track information.
  71. @param player The method pointer for the player.
  72. @param info The array of track information. This parameter is similar to the AVPTrackInfo parameter.
  73. */
  74. - (void)onTrackReady:(AliPlayer*)player info:(NSArray<AVPTrackInfo*>*)info {
  75. // Obtain the track information.
  76. }
  77. /**
  78. @brief The callback for displaying the subtitle.
  79. @param player The method pointer for the player.
  80. @param index The index number for the subtitle.
  81. @param subtitle The string of the subtitle.
  82. */
  83. - (void)onSubtitleShow:(AliPlayer*)player index:(int)index subtitle:(NSString *)subtitle {
  84. // Obtain the subtitle to display it.
  85. }
  86. /**
  87. @brief The callback for hiding the subtitle.
  88. @param player The method pointer for the player.
  89. @param index The index number for the subtitle.
  90. */
  91. - (void)onSubtitleHide:(AliPlayer*)player index:(int)index {
  92. // Hide the subtitle.
  93. }
  94. /**
  95. @brief The callback for snapshot capture.
  96. @param player The method pointer for the player.
  97. @param image The captured video image.
  98. */
  99. - (void)onCaptureScreen:(AliPlayer *)player image:(UIImage *)image {
  100. // Preview and save the snapshot.
  101. }
  102. /**
  103. @brief The callback for the completion of bitrate switching.
  104. @param player The method pointer for the player.
  105. @param info The track information after switching. This parameter is similar to the AVPTrackInfo parameter.
  106. */
  107. - (void)onTrackChanged:(AliPlayer*)player info:(AVPTrackInfo*)info {
  108. // Indicate the bitrate switching result.
  109. }
  110. //...

For more information about callback parameters, see the description of operations.

3. Set the source and prepare the playback

Four playback sources are supported: AVPVidStsSource, AVPVidAuthSource, AVPVidMpsSource, and AVPUrlSource. You can use AVPUrlSource for URL-based playback, and use AVPVidStsSource, AVPVidAuthSource, and AVPVidMpsSource for video ID (VID)-based playback. AVPVidStsSource is available for ApsaraVideo for VOD users only. AVPVidMpsSource is available for ApsaraVideo for Media Processing users only. We recommend that you do not use the AVPVidAuthSource source.

The following code uses AVPVidStsSource as an example:

  1. // Create the AVPVidStsSource object.
  2. AVPVidStsSource *source = [[AVPVidStsSource alloc] init];
  3. source.region = self. Access region;
  4. source.vid = self. VID;
  5. source.securityToken = self. Security token;
  6. source.accessKeySecret = self. Temporary AccessKey secret;
  7. source.accessKeyId = self. Temporary AccessKey ID;
  8. // Set the playback source.
  9. [self.player setStsSource:source];
  10. // Prepare the player.
  11. [self.player prepare];

For more information about playback based on ApsaraVideo for Media Processing, see Video playback.For more information about playAuth-based playback, see Use playback credentials.For more information of region settings, see VOD centers and access domains.

4. Set the UI view

If the playback source contains video images, you need to set the UI view to display the video images.

  1. self.player.playerView = self.avpPlayerView.playerView;// The displayed UI view.

5. Set playback control

You can create playback control buttons and associate the click events with the corresponding playback control methods to implement playback interaction. The basic control features include play, stop, pause, and seek. The seek feature is valid only for VOD. If you pause a live stream, the current position of the live stream is saved. You can go back to where you left off by using the resume feature. The sample code is as follows:

  1. // Start the playback.
  2. [self.player start];
  3. // Pause the playback.
  4. [self.player pause];
  5. // Stop the playback.
  6. [self.player stop];
  7. // Seek to the video image at the specified time point. Currently, this operation may not direct the video to the precise time point.
  8. [self.player seekToTime:position seekMode:AVP_SEEKMODE_INACCURATE];
  9. // Reset the player.
  10. [self.player reset];
  11. // Release the player. The player cannot be used once it is released.
  12. [self.player destroy];
  13. self.player = nil;

6. Set multi-bitrate switching

ApsaraVideo Player SDK for iOS supports playing an HTTP Live Streaming (HLS) Encryption-based video in different bitrates. After the player is prepared successfully using the prepare method, you can call the getMediaInfo method to obtain the value of the TrackInfo parameter, which indicates the bitrate information.

  1. AVPMediaInfo *info = [self.player getMediaInfo];
  2. NSArray<AVPTrackInfo*>* tracks = info.tracks;

During playback, you can call the selectTrack method to switch the bitrate.

  1. [self.player selectTrack:track.trackIndex];

You can call the onTrackChanged callback to view the bitrate switching result:

  1. - (void)onTrackChanged:(AliPlayer*)player info:(AVPTrackInfo*)info {
  2. if (info.trackType == AVPTRACK_TYPE_VIDEO) {
  3. // video changed
  4. }
  5. // etc
  6. }

7. Set autoplay

ApsaraVideo Player SDK for iOS supports autoplay. Set autoplay before calling the prepare method.

  1. self.player.autoPlay = YES;

After you set autoplay, the player automatically starts playback once it is successfully prepared. In this case, the AVPEventAutoPlayStart callback instead of the AVPEventPrepareDone callback is fired when the player is prepared.

  1. -(void)onPlayerEvent:(AliPlayer*)player eventType:(AVPEventType)eventType {
  2. switch (eventType) {
  3. case AVPEventPrepareDone: {
  4. break;
  5. case AVPEventAutoPlayStart:
  6. break;
  7. }
  8. }

8. Set loop playback

ApsaraVideo Player SDK for iOS supports loop playback. Call the loop method to enable the loop playback feature. The player plays a video all over again after it plays the video completely.

  1. self.player.loop = YES;

The callback for the start of loop playback is fired by the AVPEventLoopingStart callback.

9. Set video image rotation, scaling, and mirroring

ApsaraVideo Player SDK for iOS provides multiple operations for you to precisely control the video image, such as rotation, scaling, and mirroring.

  1. // Set the mirroring mode: horizontal image, vertical image, and no image.
  2. self.player.mirrorMode = AVP_MIRRORMODE_NONE;
  3. // Set the rotation angel: 0°, 90°, 180°, and 270°.
  4. self.player.rotateMode = AVP_ROTATE_0;
  5. // Set the scaling mode: aspect ratio-based padding, aspect ratio-based fitting, and stretching.
  6. self.player.scalingMode = AVP_SCALINGMODE_SCALEASPECTFIT;

The following table describes values of the rotateMode parameter.

Value Description
AVP_ROTATE_0 Indicates that the rotation angle is 0°, in the clockwise direction.
AVP_ROTATE_90 Indicates that the rotation angle is 90°, in the clockwise direction.
AVP_ROTATE_180 Indicates that the rotation angle is 180°, in the clockwise direction.
AVP_ROTATE_270 Indicates that the rotation angle is 270°, in the clockwise direction.

The following table describes values of the scalingMode parameter.

Value Description
AVP_SCALINGMODE_SCALEASPECTFIT Indicates that the video image is scaled down into the UI view without changing the aspect ratio. This prevents image distortion.
AVP_SCALINGMODE_SCALEASPECTFILL Indicates that the video image is scaled out to fill the UI view without changing the aspect ratio. This prevents image distortion.
AVP_SCALINGMODE_SCALETOFILL Indicates that 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.

The following table describes values of the mirrorMode parameter.

Value Description
AVP_MIRRORMODE_NONE Indicates that mirroring is disabled.
AVP_MIRRORMODE_HORIZONTAL Indicates horizontal mirroring.
AVP_MIRRORMODE_VERTICAL Indicates vertical mirroring.

10. Set the mute mode and volume control

ApsaraVideo Player SDK for iOS provides the feature of volume control. You can call the muted method to set the mute mode for the player, and call the volume method to set the player volume (valid values: 0 to 1).

  1. // Enable the mute mode.
  2. self.player.muted = YES;
  3. // Set the player volume. Value range: 0 to 1.
  4. self.player.volume = 1.0f;

11. Set the playback speed

ApsaraVideo Player SDK for iOS allows you to set the playback speed. You can call the rate method to change the playback speed from 0.5x to 2x. The audio pitch remains unchanged at different speeds.

  1. // Set the playback speed. You can change the playback speed from 0.5x to 2x.
  2. self.player.rate = 1.0f;

12. Set snapshot capture

ApsaraVideo Player SDK for iOS provides the feature of snapshot capture. When you capture a snapshot, the player saves the source data of the video image to be captured and converts the source data to a bitmap. Then, you can call the onCaptureScreen method to obtain the bitmap. Note that a snapshot is a video image and does not contain the UI.

  1. // The callback for snapshot capture.
  2. - (void)onCaptureScreen:(AliPlayer *)player image:(UIImage *)image {
  3. // Process the screenshot.
  4. }
  5. // Take a snapshot of the current video image.
  6. aliyunVodPlayer.snapshot();

13. Set play-and-cache

ApsaraVideo Player SDK for iOS provides the feature of play-and-cache. This feature saves your traffic during loop playback. To enable play-and-cache, call the AVPCacheConfig method before the prepare method is called.

To play an encrypted video, you need to configure a security file for encryption verification. For more information, see 14. Configure a security file for encryption verification.

  1. AVPCacheConfig *config = [[AVPCacheConfig alloc] init];
  2. // Enable play-and-cache.
  3. config.enable = YES;
  4. // Specify the maximum length of a single cached file. Files whose length exceeds the maximum value are not cached.
  5. config.maxDuration = 100;
  6. // Specify the cache directory. Specify it as required by your application.
  7. config.path = @"please use your cache path here";
  8. // Specify the maximum size of the cache directory. When the total size of cached files in the cache directory exceeds the maximum size, the system overwrites the earliest cached files.
  9. config.maxSizeMB = 200;
  10. // Specify the cache configuration for the player.
  11. [self.player setCacheConfig:config];

You must call the setCacheConfig method to use cached files. Cached files are used in the following scenarios:

  1. If you enable loop playback, the player automatically plays a video all over again by using the cached file after it plays the video completely.
  2. After you cache a video and create a new player to play the video, the new player plays the video by using the cached file.

Note: The player needs to locate cached files for VID-based playback based on the VID and other required information, which can be obtained through online requests.

ApsaraVideo Player SDK also provides an operation for you to obtain the cache file directory:

  1. -(NSString *) getCacheFilePath:(NSString *)URL;
  2. Feature: Obtain the cached file name based on the video URL. Call the setCacheConfig method to obtain the name of the cached file based on the URL.
  3. Parameter: url: the video URL.
  4. Return value: the absolute path for the cached file.
  5. -(NSString *) getCacheFilePath:(NSString *)vid format:(NSString *)format definition:(NSString *)definition;
  6. Feature: Obtain the cached file name based on the VID. Call the setCacheConfig method to obtain the name of the cached file based on the VID.
  7. Parameters: vid: the video ID. format: the video format. definition: the video resolution. previewTime: the preview duration.
  8. Return value: the absolute path for the cached file.

The player does not cache videos during playback in some scenarios. The following provides more information about the play-and-cache feature:
1. When the player plays AVPUrlSource streams by using the HLS protocol based on the URL in an M3U8 file, the player does not cache the video during playback. For other supported formats of URL-based playback, the player caches videos during playback as configured.
2. When the player plays a video based on the VID, the player caches the video during playback as configured.
3. A video is successfully cached when the player reads all video data. Caching may fail if the stop method or the onError method is called before data reading is complete.
4. Seeking to a position inside the cached video does not affect the caching result, but seeking to a position outside the cached video may cause a caching failure.
5. To cache an encrypted video, ensure that the App matches with the authentication information in the security file of the video. Otherwise, the video caching may fail.
6. The onPlayerEventInfo callback returns the caching result.

  1. -(void)onPlayerEvent:(AliPlayer*)player eventWithString:(AVPEventWithString)eventWithString description:(NSString *)description {
  2. if (eventWithString == EVENT_PLAYER_CACHE_SUCCESS) {
  3. // Indicate that the caching succeeds.
  4. }else if (eventWithString == EVENT_PLAYER_CACHE_ERROR) {
  5. // Indicate that the caching failed.
  6. }
  7. }

14. Set preview

ApsaraVideo Player SDK provides the preview feature. After you set the preview duration, the player plays the video clip for preview instead of the whole video.
You can set the preview feature by using ApsaraVideo for VOD. Currently, this feature supports VidSts and VidAuth sources. For more information about how to configure and use the preview feature, see Best practice of preview. After you enable the preview feature, you can call the setPreviewTime method in VidPlayerConfigGen to set the preview duration. The following code uses AVPVidStsSource as an example:

  1. AVPVidStsSource *source = [[AVPVidStsSource alloc] init];
  2. ....
  3. VidPlayerConfigGenerator* vp = [[VidPlayerConfigGenerator alloc] init];
  4. [vp setPreviewTime:20];// Specify the preview duration to 20 seconds.
  5. source.playConfig = [vp generatePlayerConfig];// Specify the settings for the playback source.
  6. ...

You can use the VidPlayerConfigGen method to specify request parameters supported by the server. For more information, see Request parameters.

15. Enable or disable hard decoding

ApsaraVideo Player SDK for iOS supports H.264 and H.265 hard decoding. You can call the enableHardwareDecoder method to enable or disable hard decoding. By default, the hard decoding feature is enabled. If the hard decoding failed to be initialized, it is switched to soft decoding to ensure normal playback.

  1. // Enable hard decoding. It is enabled by default.
  2. self.player.enableHardwareDecoder = YES;

The onPlayerEvent method fires a callback when hard decoding is switched to soft decoding.

  1. -(void)onPlayerEvent:(AliPlayer*)player eventWithString:(AVPEventWithString)eventWithString description:(NSString *)description {
  2. if (eventWithString == EVENT_SWITCH_TO_SOFTWARE_DECODER) {
  3. // Switch to soft decoding.
  4. }
  5. }

16. Set the referer

ApsaraVideo Player SDK for iOS provides the AVPConfig class for you to set the request referer. By setting referers in the blacklist or whitelist in the ApsaraVideo for VOD console, you can implement access control. The sample code is as follows:

  1. // Obtain player parameters.
  2. AVPConfig *config = [self.player getConfig];
  3. // Set the referer.
  4. config.referer = referer;
  5. ... // Set other parameters.
  6. // Specify the settings for the player.
  7. [self.player setConfig:config];

17. Specify UserAgent

ApsaraVideo Player SDK for iOS provides the AVPConfig class for you to specify the request UserAgent. After you specify UserAgent, the player contains the UserAgent information in its requests. The sample code is as follows:

  1. // Obtain player parameters.
  2. AVPConfig *config = [self.player getConfig];
  3. // Set UserAgent.
  4. config.userAgent = userAgent;
  5. ... // Set other parameters.
  6. // Specify the settings for the player.
  7. [self.player setConfig:config];

18. Specify the network timeout period and retry times

You can use the AVPConfig class to set the network timeout period and retry times. The sample code is as follows:

  1. // Obtain player parameters.
  2. AVPConfig *config = [self.player getConfig];
  3. // Specify the network timeout period, in milliseconds.
  4. config.networkTimeout = 5000;
  5. // Specify retry times upon a network timeout. The networkTimeout parameter indicates the retry interval. The networkRetryCount parameter indicates the retry times. A value of 0 indicates that the player does not retry playback upon a network timeout. The application determines the retry times. The default value is 2.
  6. config.networkRetryCount = 2;
  7. ... // Set other parameters.
  8. // Specify the settings for the player.
  9. [self.player setConfig:config];
  1. If you set the networkRetryCount parameter to a value other than 0, the player retries playback when the player starts loading data due to a network error. The number of retry times equals the value of the networkRetryCount parameter. The retry interval equals the value of the networkTimeout parameter. If the player is still loading data when the retry times exceed the maximum limit, the onError callback is fired. You can call the AVPErrorModel.code method to obtain the error code: ERROR_LOADING_TIMEOUT.
  2. If you set the networkRetryCount parameter to 0, the onPlayerEvent callback is fired when the network connection times out. You can call the eventWithString method to obtain the information code: EVENT_PLAYER_NETWORK_RETRY. To resolve the problem, call the reload method to reload data or take other operations as required.

19. Control the buffer and delay

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 iOS provides the AVPConfig class for you to control the buffer and delay.

  1. // Obtain player parameters.
  2. AVPConfig *config = [self.player getConfig];
  3. // Set the maximum buffer delay. This parameter is valid only for live streaming. If the delay time exceeds the maximum limit, the player synchronizes frames to reduce the delay under the set limit.
  4. config.maxDelayTime = 5000;
  5. // Set the maximum buffer duration, in milliseconds. This parameter indicates the maximum video length that can be loaded by the player.
  6. config.maxBufferDuration = 50000;
  7. // Set the peak buffer duration, in milliseconds. The player starts loading data when the network connection is poor. This parameter indicates the buffer duration beyond which the player stops loading in this case.
  8. config.highBufferDuration = 3000;
  9. // Set the startup loading duration, in milliseconds. The smaller this value is, the shorter the startup loading time is, and the sooner the player starts loading after the start of playback.
  10. config.startBufferDuration = 500;
  11. // Set other parameters.
  12. // Specify the settings for the player.
  13. [self.player setConfig:config];

Note: Ensure that the value of startBufferDuration is not greater than the value of highBufferDuration, and the value of highBufferDuration is not greater than the value of maxBufferDuration.

20. Set HTTP headers

ApsaraVideo Player SDK provides the AVPConfig class to set HTTP headers for the player. The sample code is as follows:

  1. // Obtain player parameters.
  2. AVPConfig *config = [self.player getConfig];
  3. // Define a header.
  4. NSMutableArray *httpHeaders = [[NSMutableArray alloc] init];
  5. // You need to set a host when using Alibaba Cloud HTTPDNS.
  6. [httpHeaders addObject:@"Host:xxx.com"];
  7. // Set the header.
  8. config.httpHeaders = httpHeaders;
  9. ... // Set other parameters.
  10. // Specify the settings for the player.
  11. [self.player setConfig:config];

2. List playback

Currently, list playback for short videos is popular. ApsaraVideo Player SDK for iOS provides a complete list playback feature with the preloading mechanism. This significantly shortens the startup loading time. The list playback procedure is as follows:

  1. Create a player. 2. Set listeners. 3. Add multiple playback sources. 4. Play a playback source. 5. Set operations for playback control. 6. Remove a playback source. 7. Release the player.

Features and operations of playback for list playback are same as those in Playback, except that some list control features are added. For more information about creation, listening, control, and release of the player, see Playback.

1. Create a player

AliListPlayer and AliPlayer provide almost the same features, except that AliListPlayer provides a feature of list playback. To use the list playback feature, create an AliListPlayer player as follows:

  1. self.listPlayer = [[AliListPlayer alloc] init];

2. Specify the number of short videos to be preloaded

You can significantly shorten the startup loading time by properly setting the number of short videos to be preloaded.

  1. // Specify the number of short videos to be preloaded. Total number of short videos to be preloaded = 1 + count × 2, where, count is the value of the setPreloadCount parameter.
  2. self.listplyer.preloadCount = 2;

3. Add or remove multiple playback sources

List playback supports AVPVidStsSource and AVPUrlSource sources. You can use AVPUrlSource for URL-based playback, and use AVPVidStsSource for VID-based playback.

AVPVidAuthSource and AVPVidMpsSource sources are not supported by list playback.

  1. // Add an AVPVidStsSource source.
  2. [self.listPlayer addVidSource:videoId uid:UUIDString];
  3. // Add an AVPUrlSource source.
  4. [self.listPlayer addUrlSource:URL uid:UUIDString];
  5. // Remove a source.
  6. [self.listPlayer removeSource:UUIDString];

The uid parameter indicates the unique ID of a video, which is used to differentiate videos. Videos with the same unique ID are considered as the same video.If the player plays a video that is not the one you specified, check whether you specify a unique ID for multiple videos.

4. Play a playback source

After you add one or more playback sources, you can call the following operations to play a source:

  1. // Use this operation for URL-based playback.
  2. - (BOOL) moveTo:(NSString*)uid;
  3. // Use this operation for VID-based playback. You need to specify the STS token information for the stsInfo parameter. Ensure that the STS token is valid.
  4. - (BOOL) moveTo:(NSString*)uid accId:(NSString*)accId accKey:(NSString*)accKey token:(NSString*)token region:(NSString*)region;

5. Play the previous or next video in the list

You can call the moveToPrev method to play the previous video, and call the moveToNext method to play the next video.

  1. // Play the next video. This method is valid only for URL-based playback, and not valid for VID-based playback.
  2. - (BOOL) moveToNext;
  3. // Play the previous video. This method is valid only for URL-based playback, and not valid for VID-based playback.
  4. - (BOOL) moveToPre;
  5. // Play the next video. This method is valid only for VID-based playback.
  6. - (BOOL) moveToNext:(NSString*)accId accKey:(NSString*)accKey token:(NSString*)token region:(NSString*)region;
  7. // Play the previous video. This method is valid only for VID-based playback.
  8. - (BOOL) moveToPre:(NSString*)accId accKey:(NSString*)accKey token:(NSString*)token region:(NSString*)region;

3. Video download

ApsaraVideo Player SDK allows you to download videos from ApsaraVideo for VOD by using the STS token and playAuth. ApsaraVideo for VOD supports two download modes: secure download and normal download. You can set the download mode in the console.
When you select the normal download mode, downloaded videos are not encrypted by Alibaba Cloud, even though the videos have been encrypted by ApsaraVideo for VOD. That means 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 for VOD. That means you cannot use third-party players other than ApsaraVideo Player to play the downloaded videos.

The process for video download is as follows:

  1. Create and set a download object. 2. Set listeners. 3. Prepare the download source. 4. Select download tasks. 5. Update the download source information and start download. 6. Release the download object after the download succeeds or fails.

1. Create and set a download object

Create a download object. The sample code is as follows:

  1. AliMediaDownloader *downloader = [[AliMediaDownloader alloc] init];
  2. [downloader setSaveDirectory:self.downLoadPath];
  3. [downloader setDelegate:self];

ApsaraVideo Player SDK for iOS allows you to download videos encrypted by Alibaba Cloud. You need to configure a security file for encryption verification in the player SDK to ensure security. We recommend that you configure the security file in your application, and you only need to do that once.

  1. NSString *encrptyFilePath = [[NSBundle mainBundle] pathForResource:@"encryptedApp" ofType:@"dat"];
  2. [AliPrivateService initKey:encrptyFilePath];

To download an encrypted video, ensure that the application information matches the authentication information in the security file of the video. Otherwise, the video download may fail.

2. Set listeners

The download object provides multiple listeners. Use the following code to set listeners:

  1. -(void)onPrepared:(AliMediaDownloader *)downloader mediaInfo:(AVPMediaInfo *)info {
  2. // Indicate that the preparation of download tasks succeeds.
  3. }
  4. -(void)onError:(AliMediaDownloader *)downloader errorModel:(AVPErrorModel *)errorModel {
  5. // Indicate that a download error occurs.
  6. }
  7. -(void)onDownloadingProgress:(AliMediaDownloader *)downloader percentage:(int)percent {
  8. // Indicate the percentage of the download progress.
  9. }
  10. -(void)onProcessingProgress:(AliMediaDownloader *)downloader percentage:(int)percent {
  11. // Indicate the percentage of the processing progress.
  12. }
  13. -(void)onCompletion:(AliMediaDownloader *)downloader {
  14. // Indicate that the download succeeds.
  15. }

3. Prepare the download source

Call the prepare method to prepare the download source. ApsaraVideo Player SDK for iOS supports two download sources: AVPVidStsSource and AVPVidAuthSource. The following code uses AVPVidStsSource as an example:

  1. // Create the AVPVidStsSource object.
  2. AVPVidStsSource* stsSource = [[AVPVidStsSource alloc] init];
  3. stsSource.vid = source.vid;// The video ID.
  4. stsSource.region = DEFAULT_SERVER.region;// The access region.
  5. stsSource.securityToken = DEFAULT_SERVER.securityToken;// The security token.
  6. stsSource.accessKeySecret = DEFAULT_SERVER.accessKeySecret;// The temporary AccessKey secret.
  7. stsSource.accessKeyId = DEFAULT_SERVER.accessKeyId;// The temporary AccessKey ID.
  8. // Prepare the download source.
  9. [downloader prepareWithVid:stsSource];

4. Select download tasks

When the download source preparation is completed, the onPrepared callback is fired. Select a video track for download:

  1. -(void)onPrepared:(AliMediaDownloader *)downloader mediaInfo:(AVPMediaInfo *)info {
  2. NSArray<AVPTrackInfo*>* tracks = info.tracks;
  3. // Download the information of tracks, for example, the first track.
  4. [downloader selectTrack:[tracks objectAtIndex:0].trackIndex];
  5. }

5. Update the download source information and start download

After you select download tasks and download the track information, you can start the download. We recommend that you update the download source information before the download in case of AVPVidStsSource or AVPVidAuthSource expiration.

  1. // Update the download source information.
  2. [downloader updateWithVid:vidSource]
  3. // Start the download.
  4. [downloader start];

6. Release the download object after the download succeeds or fails

After the download succeeds, call the destroy method to release the download object.

  1. [self.downloader destroy];
  2. self.downloader = nil;