This topic provides examples of how to use the advanced features of ApsaraVideo Player SDK for iOS. For a complete guide to all features, see the API reference.
To run the demo, you can download it and follow the instructions in Run the demo to compile and run the project.
Verify professional capabilities
Some features of ApsaraVideo Player require a Professional Edition license. For more information, see Features of ApsaraVideo Player SDK. To use these features, you must obtain a license as described in Obtain a license for ApsaraVideo Player SDK.
You can set the listener when the application starts or before you call any player API operations.
void premiumVeryfyCallback(AVPPremiumBizType biztype, bool isValid, NSString* errorMsg) {
NSLog(@"onPremiumLicenseVerifyCallback: %d, isValid: %d, errorMsg: %@", biztype, isValid, errorMsg);
}
[AliPrivateService setOnPremiumLicenseVerifyCallback:premiumVeryfyCallback];AVPPremiumBizType is an enumeration type for premium features. When a related feature is used, the player validates the feature and returns the result through this callback. If isValid is false, errorMsg contains the specific reason.
Playback
List playback
ApsaraVideo Player SDK for iOS provides comprehensive list playback features for typical list playback scenarios. These features, combined with mechanisms such as preloading, significantly improve the first frame loading speed for short videos.
For a better list playback experience, we recommend that you use our short-form video drama solution. For more information, see Client-side development for short-form video dramas.
Play videos with transparency
Feature description
ApsaraVideo Player SDK supports rendering the alpha channel to create dynamic effects for transparent gifts. In scenarios such as live channels, you can play dynamic effects of transparent gifts without blocking the content in the live channel. This significantly improves the user viewing and interaction experience.
Limits
The transparent rendering feature is supported in All-in-One SDK V6.8.0 and later or ApsaraVideo Player SDK V6.9.0 and later.
Advantages
Using MP4 videos with transparency information as gift effects provides better animation quality, smaller file sizes, higher compatibility, and higher development efficiency. This allows gift effects to be displayed to users and improves the user experience.
Better animation quality: MP4 videos can retain the original animation quality, including details and colors. Compared with other formats such as APNG or IXD, MP4 can more accurately restore the animation effects that are created by designers.
Smaller file size: MP4 video files can be more effectively compressed than other formats such as APNG or IXD. This improves loading speed and reduces network bandwidth consumption.
Higher compatibility: MP4 is a universal video format that is widely supported on various devices and browsers. It lets you play and watch gift effects on mainstream devices.
Higher development efficiency: The technical solution of using MP4 videos as gift effects is relatively simple. Developers do not need to research and implement complex parsing and rendering logic. This allows developers to focus on other features and improve development efficiency.
Metal rendering
ApsaraVideo Player SDK for iOS supports video rendering using the Metal framework.
Currently, only the background color, scaling mode, and Picture-in-Picture (PiP) features are supported.
Configuration item
/**
@brief The video rendering type. 0 indicates the default renderer. 1 indicates the mixed renderer. Default value: 0.
*/
@property(nonatomic, assign) int videoRenderType;Usage example
AVPConfig *config = [self.player getConfig];
// Use the Metal rendering method.
config.videoRenderType = 1;
[self.player setConfig:config];
[self.player prepare];External captions
For detailed code examples, see the External Subtitle Demo and Switching (ExternalSubtitle) module in API-Example. This project is an Objective-C-based sample project for ApsaraVideo Player SDK for iOS that helps developers quickly integrate core SDK features.
ApsaraVideo Player SDK for iOS supports adding and switching external captions. The SDK supports SRT, SSA, ASS, and VTT caption formats.
The following code provides an example:
Create a view to display captions.
You can create different views for different caption formats.
// Initialize the custom subTitleLabel. UILabel *subTitleLabel = [[UILabel alloc] initWithFrame:frame]; // Add the caption to the custom superView. superView is the parent view that exists in the custom interface. [superView addSubview:subTitleLabel];Set caption-related listeners.
// An external caption is added. - (void)onSubtitleExtAdded:(AliPlayer*)player trackIndex:(int)trackIndex URL:(NSString *)URL {} // Callback for caption header information. - (void)onSubtitleHeader:(AliPlayer *)player trackIndex:(int)trackIndex Header:(NSString *)header{} // Callback for displaying captions. - (void)onSubtitleShow:(AliPlayer*)player trackIndex:(int)trackIndex subtitleID:(long)subtitleID subtitle:(NSString *)subtitle { subTitleLabel.text =subtitle; subTitleLabel.tag =subtitleID; } // Callback for hiding captions. - (void)onSubtitleHide:(AliPlayer*)player trackIndex:(int)trackIndex subtitleID:(long)subtitleID{ [subTitleLabel removeFromSuperview]; }Add a caption.
[self.player addExtSubtitle:URL];Switch captions.
[self.player selectExtSubtitle:trackIndexenable:YES];
Audio-only playback
You can disable video playback to achieve audio-only playback. You must configure PlayerConfig before you prepare the player.
AVPConfig *config = [self.player getConfig];
config.disableVideo = YES;
[self.player setConfig:config];Switch between software and hardware decoding
ApsaraVideo Player SDK for iOS provides hardware decoding capabilities for H.264 and H.265. It also provides the enableHardwareDecoder switch. This switch is enabled by default. If hardware decoding fails to initialize, the player automatically switches to software decoding to ensure normal video playback. The following code provides an example:
// Enable hardware decoding. This is enabled by default.
self.player.enableHardwareDecoder = YES;If the player automatically switches from hardware decoding to software decoding, the onPlayerEvent callback is invoked. The following code provides an example:
-(void)onPlayerEvent:(AliPlayer*)player eventWithString:(AVPEventWithString)eventWithString description:(NSString *)description {
if (eventWithString == EVENT_SWITCH_TO_SOFTWARE_DECODER) {
// Switched to software decoding.
}
}Adaptive H.265 playback
If the current device model is in the cloud-based H.265 blacklist model library or if hardware decoding of an H.265 stream fails, adaptive fallback is triggered. The fallback process is as follows: If an H.264 backup stream is set, the H.264 backup stream is automatically played. If no H.264 backup stream is set, the player automatically falls back to H.265 software decoding.
This feature is enabled only after you activate the value-added service of adaptive decoding combined with cloud and client. You must submit a Yida form to apply for a license.
The value-added service of adaptive decoding combined with cloud and client mainly includes: 1. Dynamic delivery of cloud-based hardware decoding compatibility data. 2. Adaptive fallback from H.265 streams to H.264 streams.
The SDK can still automatically switch to software decoding when hardware decoding fails, even if the value-added service is not enabled.
The following code shows how to set a backup stream:
// The application layer maintains a map that stores all key-value pairs of original URLs and backup URLs. When switching, query the backup URL in the map based on the original URL.
NSString* getBackupUrlCallback(AVPBizScene scene, AVPCodecType codecType, NSString* oriurl){
NSMutableDictionary *globalMap = [AliPlayerViewController getGlobalBackupUrlMap];
NSString *backupUrl = globalMap[oriurl];
return backupUrl;
}
[AliPlayerGlobalSettings setAdaptiveDecoderGetBackupURLCallback:getBackupUrlCallback];Adaptively switch video definition based on network conditions
You can generate HLS multi-bitrate adaptive video streams by transcoding them using a video packaging transcoding template group in ApsaraVideo VOD. For more information, see Configure adaptive bitrate streaming for ApsaraVideo VOD.
If you play an adaptive stream that is transcoded by ApsaraVideo VOD using the Vid method, you must set the default playback definition list to
AUTOto obtain and play the adaptive video stream. Otherwise, the player selects a low-definition video stream for playback based on the default logic. For more information about the default playback order of definitions, see If a video is transcoded into multiple definitions, which definition does the player SDK play by default?. The following code shows how to specify the definition list for VidAuth playback:AVPVidAuthSource *authSource = [[AVPVidAuthSource alloc] init]; authSource.definitions = @"AUTO";
ApsaraVideo Player SDK for iOS supports multi-bitrate adaptive HLS and DASH video streams. After prepare is successful, you can call getMediaInfo to obtain the information of each bitrate stream, which is TrackInfo. The following code provides an example:
AVPMediaInfo *info = [self.player getMediaInfo];
NSArray<AVPTrackInfo*>* tracks = info.tracks;During playback, you can call the player's selectTrack method to switch the playback bitrate stream. If the value is SELECT_AVPTRACK_TYPE_VIDEO_AUTO, the stream is multi-bitrate adaptive. The following code provides an example:// Switch bitrates.
[self.player selectTrack:track.trackIndex];
// Switch bitrates and adapt.
[self.player selectTrack:SELECT_AVPTRACK_TYPE_VIDEO_AUTO];
// Switch the bitrate.
[self.player selectTrack:track.trackIndex];
// Enable adaptive bitrate streaming.
[self.player selectTrack:SELECT_AVPTRACK_TYPE_VIDEO_AUTO];The result of the switch is returned in the onTrackChanged listener callback. The following code provides an example:
- (void)onTrackChanged:(AliPlayer*)player info:(AVPTrackInfo*)info {
if (info.trackType == AVPTRACK_TYPE_VIDEO) {
// video changed
}
// etc
}Optional: Before you call the player's selectTrack method to switch the playback bitrate stream to ABR, you can set the upper limit of the definition for ABR switching through config. This prevents the player from automatically switching to an unexpected bitrate. The following code provides an example: (We recommend that you call the following code before the player calls the prepare method or the list player calls the moveTo method to make it effective.)
AVPConfig *config = [self.player getConfig];
config.maxAllowedAbrVideoPixelNumber = 921600; // Set the maximum number of pixels for ABR definition to 921600 (width × height = 1280 × 720), so that the number of pixels for the definition that ABR can switch to is less than or equal to this value.
[self.player setConfig:config];Take snapshots
ApsaraVideo Player SDK for iOS provides a feature to take a snapshot of the current video. This feature is implemented by the snapShot API operation. The original data is captured, converted to a bitmap, and then returned. The callback interface is onCaptureScreen. The following code provides an example:
// Snapshot callback.
- (void)onCaptureScreen:(AliPlayer *)player image:(UIImage *)image {
// Process the snapshot.
}
// Take a snapshot of the current playback screen.
[self.player snapShot];The snapshot does not include the interface.
Preview
ApsaraVideo Player SDK for iOS, in conjunction with ApsaraVideo VOD configurations, can implement a preview feature. It supports both VidSts and VidAuth (recommended for ApsaraVideo VOD) playback methods. For more information about how to configure and use the preview feature, see Preview videos.
After you configure the preview feature, you can use the setPreviewTime method of the VidPlayerConfigGen interface to set the preview duration for the player. The following code shows an example for VidSts playback:
AVPVidStsSource *source = [[AVPVidStsSource alloc] init];
....
VidPlayerConfigGenerator* vp = [[VidPlayerConfigGenerator alloc] init];
[vp setPreviewTime:20]; // 20-second preview.
source.playConfig = [vp generatePlayerConfig]; // Set for the playback source.
...When you set the preview duration and play a video using ApsaraVideo Player SDK for iOS, the server does not return the full video content. Instead, the server returns the content for the preview period.
VidPlayerConfigGen supports setting request parameters that are supported by the server. For more information, see Request parameters.
Set the Referer
ApsaraVideo Player SDK for iOS lets you set the Referer. In conjunction with the Referer blacklists and whitelists in the console, you can control access permissions. You can use the AVPConfig method to set the request Referer. The following code shows an example for ApsaraVideo Player SDK for iOS:
// First, get the configuration.
AVPConfig *config = [self.player getConfig];
// Set the Referer.
config.referer = referer;
....// Other settings.
// Set the configuration for the player.
[self.player setConfig:config];Set the User-Agent
ApsaraVideo Player SDK for iOS provides AVPConfig to set the request User-Agent (UA). After you set the UA, the player's requests include the UA information. The following code provides an example:
// First, get the configuration.
AVPConfig *config = [self.player getConfig];
// Set the User-Agent.
config.userAgent = userAgent;
....// Other settings.
// Set the configuration for the player.
[self.player setConfig:config];Configure network retry time and count
You can set the network timeout and retry count for ApsaraVideo Player SDK for iOS using the AVPConfig method. The following code provides an example:
// First, get the configuration.
AVPConfig *config = [self.player getConfig];
// Set the network timeout in milliseconds.
config.networkTimeout = 5000;
// Set the number of retry attempts on timeout. The interval for each retry is networkTimeout. networkRetryCount=0 means no retries, and the retry policy is determined by the app. The default value is 2.
config.networkRetryCount = 2;
....// Other settings.
// Set the configuration for the player.
[self.player setConfig:config];If you set networkRetryCount, the player retries networkRetryCount times if a network problem occurs and causes a loading state. The interval for each retry is networkTimeout.
If the loading state persists after multiple retries, the
onErrorevent is called. In this case, AVPErrorModel.code is ERROR_LOADING_TIMEOUT.If networkRetryCount is set to 0, when the network retry times out, the player calls onPlayerEvent with the parameter eventWithString set to EVENT_PLAYER_NETWORK_RETRY. At this point, you can call the player's
reloadmethod to reload the network or perform other actions.
Configure caching and latency control
Cache control is very important for a player. Proper configuration can effectively speed up first frame loading and reduce stuttering. ApsaraVideo Player SDK for iOS provides interfaces for setting cache and latency control through AVPConfig. The following code provides an example:
// First, get the configuration.
AVPConfig *config = [self.player getConfig];
// Maximum latency. Note: This is effective for live streaming. When the latency is high, the player SDK will perform frame synchronization to ensure the latency is within this range.
config.maxDelayTime = 5000;
// Maximum buffer duration in milliseconds. The player loads at most this duration of buffered data each time.
config.maxBufferDuration = 50000;
// High buffer duration in milliseconds. When data is being loaded due to poor network conditions, if the loaded buffer duration reaches this value, the loading state ends.
config.highBufferDuration = 3000;
// Start buffer duration in milliseconds. The shorter this time is set, the faster the first frame loads. It may also cause the player to enter a loading state soon after playback starts.
config.startBufferDuration = 500;
// Other settings.
// Set the configuration for the player.
[self.player setConfig:config];The relationship between the three buffer durations must be: startBufferDuration ≤ highBufferDuration ≤ maxBufferDuration.
If the maximum buffer duration (mMaxBufferDuration) is greater than 5 minutes, the system defaults to 5 minutes to prevent memory exceptions that are caused by an excessively large buffer.
Set HTTP headers
Using the AVPConfig method, you can add HTTP header parameters to the player's requests. The following code provides an example:
// First, get the configuration.
AVPConfig *config = [self.player getConfig];
// Define the header.
NSMutableArray *httpHeaders = [[NSMutableArray alloc] init];
// For example, when using HTTPDNS, you need to set the Host.
[httpHeaders addObject:@"Host:example.com"];
// Set the header.
config.httpHeaders = httpHeaders;
....// Other settings.
// Set the configuration for the player.
[self.player setConfig:config];Picture-in-Picture (PiP)
For detailed code examples, see the Picture-in-Picture (PictureInPicture) module in API-Example. This project is an Objective-C-based sample project for ApsaraVideo Player SDK for iOS that helps developers quickly integrate core SDK features.
Environment requirements for the PiP feature: iOS 15 or later, ApsaraVideo Player SDK for iOS V5.4.9.0 or later.
Versions of ApsaraVideo Player SDK for iOS earlier than 5.5.2.0 provide methods only to enable and disable PiP, and to display the PiP window when the app is in the background. Starting from version 5.5.2.0, the SDK supports setting the PiP delegate from the outside, which allows for more personalized PiP feature development.
To enable the PiP feature, make sure the PiP function is enabled in your phone's settings ().
Enable PiP
After you enable the PiP feature, the video continues to play in a small PiP window when the application is moved to the background. When the application is brought back to the foreground, the video resumes its original playback format. The PiP feature is controlled by the setPictureInPictureEnable switch. To enable the PiP feature, you need to do so in the AVPEventPrepareDone state. The following code shows an example of how to enable the PiP feature:
- (void)onPlayerEvent:(AliPlayer *)player eventType:(AVPEventType)eventType {
switch (eventType) {
case AVPEventPrepareDone:
{
[self.player setPictureInPictureEnable:YES];
}
break;
default:
break;
}
}When the player calls stop to stop playback, the PiP window is no longer needed. You must first disable PiP using the setPictureInPictureEnable switch, and then call stop.
Set the PiP delegate
The following section provides only some common code examples for interactions between the Picture-in-Picture (PiP) window and the player window. These examples include the logic for the pause, play, fast forward, and fast backward buttons in the PiP window, and for replaying. For details about the delegate methods, see the content of the AliPlayerPictureInPictureDelegate.h header file in the AliyunPlayer.framework of the SDK folder in the Player SDK Demo.
Set the PiP delegate.
/** * @brief Set the PiP delegate. */ -(void) setPictureinPictureDelegate:(id<AliPlayerPictureInPictureDelegate>)delegate; // Set the PiP delegate. [self.player setPictureinPictureDelegate:self];Add variables and implement the delegate interface.
Add global variables to control the player's state changes.
#import "YourUIViewController.h" #import <AliyunPlayer/AliyunPlayer.h> @interface YourUIViewController () <AVPDelegate, AliPlayerPictureInPictureDelegate> // Player instance. @property (nonatomic, strong) AliPlayer *player; // Player view container. @property (nonatomic, strong) UIView *playerView; // Listen for whether PiP is currently paused. @property (nonatomic, assign) BOOL isPipPaused; // Listen for the current playback status of the player, set through the newStatus callback of the playback event status change listener. @property (nonatomic, assign) AVPStatus currentPlayerStatus; // Set the PiP controller. Set it in the callback method that is invoked before PiP starts. You must actively set it to nil when the page is about to be destroyed. We recommend setting this. @property (nonatomic, weak) AVPictureInPictureController *pipController; // Listen for the current playback progress of the player. Set currentPosition to the value of the position parameter in the callback for the current video playback position. @property (nonatomic, assign) int64_t currentPosition; @endNotepipController must be modified with weak or assign. If you use assign, pay attention to when the variable is set to null.
When you listen to the playback event status change callback interface, you must actively call the following method to update the relevant status of the PiP controller.
- (void)onPlayerStatusChanged:(AliPlayer*)player oldStatus:(AVPStatus)oldStatus newStatus:(AVPStatus)newStatus { self.currentPlayerStatus = newStatus; if (_pipController) { [self.pipController invalidatePlaybackState]; } }When you listen to the playback event callback interface, you must actively call the following method to update the relevant status of the PiP controller.
- (void)onPlayerEvent:(AliPlayer*)player eventType:(AVPEventType)eventType { if (eventType == AVPEventCompletion) { if (_pipController) { self.isPipPaused = YES; // After playback ends, change the PiP status to paused. [self.pipController invalidatePlaybackState]; } } else if (eventType == AVPEventSeekEnd) { // Seeking is complete. if (_pipController) { [self.pipController invalidatePlaybackState]; } } }Set listeners.
Listen for the callback that is invoked before PiP starts.
/** @brief PiP is about to start. @param pictureInPictureController The PiP controller. */ - (void)pictureInPictureControllerWillStartPictureInPicture:(AVPictureInPictureController *)pictureInPictureController { if (!_pipController) { self.pipController = pictureInPictureController; } self.isPipPaused = !(self.currentPlayerStatus == AVPStatusStarted); [pictureInPictureController invalidatePlaybackState]; }Listen for the callback that is invoked before PiP stops.
/** @brief PiP is about to stop. @param pictureInPictureController The PiP controller. */ - (void)pictureInPictureControllerWillStopPictureInPicture:(AVPictureInPictureController *)pictureInPictureController { self.isPipPaused = NO; [pictureInPictureController invalidatePlaybackState]; }Listen for the callback that is invoked to restore the user interface before PiP stops.
/** @brief Tells the delegate to restore the user interface before PiP stops. @param pictureInPictureController The PiP controller. @param completionHandler Call and pass YES to allow the system to finish restoring the player user interface. */ - (void)pictureInPictureController:(AVPictureInPictureController *)pictureInPictureController restoreUserInterfaceForPictureInPictureStopWithCompletionHandler:(void (^)(BOOL restored))completionHandler { if (_pipController) { _pipController = nil; } completionHandler(YES); }Listen for the callback that sets the playable time range in PiP mode.
/** @brief Notifies the PiP controller of the current playable time range. @param pictureInPictureController The PiP controller. @return The current playable time range. */ - (CMTimeRange)pictureInPictureControllerTimeRangeForPlayback:(nonnull AVPictureInPictureController *)pictureInPictureController layerTime:(CMTime)layerTime{ Float64 current64 = CMTimeGetSeconds(layerTime); Float64 start; Float64 end; if (currentPosition <= self.player.duration) { double curPostion = self.currentPosition / 1000.0; double duration = self.player.duration / 1000.0; double interval = duration - curPostion; start = current64 - curPostion; end = current64 + interval; CMTime t1 = CMTimeMakeWithSeconds(start, layerTime.timescale); CMTime t2 = CMTimeMakeWithSeconds(end, layerTime.timescale); return CMTimeRangeFromTimeToTime(t1, t2); } else { return CMTimeRangeMake(kCMTimeNegativeInfinity, kCMTimePositiveInfinity); } }Listen for the callback that indicates whether the video is paused in PiP mode.
/** @brief Reflects the paused or playing state on the UI. @param pictureInPictureController The PiP controller. @return Paused or playing. */ - (BOOL)pictureInPictureControllerIsPlaybackPaused:(nonnull AVPictureInPictureController *)pictureInPictureController{ return self.isPipPaused; }NoteThis callback is triggered before PiP starts. Make sure that the return value of this callback is false at this time. Otherwise, PiP cannot be activated.
Listen for the callback that is invoked when the user taps the fast-forward or rewind button in PiP mode and synchronize the player status.
/** @brief The user taps the fast-forward or rewind button. @param pictureInPictureController The PiP controller. @param skipInterval The time interval for fast-forwarding or rewinding. @param completionHandler A closure that must be called to indicate that the seeking operation is complete. */ - (void)pictureInPictureController:(nonnull AVPictureInPictureController *)pictureInPictureController skipByInterval:(CMTime)skipInterval completionHandler:(nonnull void (^)(void))completionHandler { int64_t skipTime = skipInterval.value / skipInterval.timescale; int64_t skipPosition = self.currentPosition + skipTime * 1000; if (skipPosition < 0) { skipPosition = 0; } else if (skipPosition > self.player.duration) { skipPosition = self.player.duration; } [self.player seekToTime:skipPosition seekMode:AVP_SEEKMODE_INACCURATE]; [pictureInPictureController invalidatePlaybackState]; }Listen for the callback that is invoked when the user taps the pause or play button in PiP mode.
/** @brief The user taps the pause button in PiP mode. @param pictureInPictureController The PiP controller. @param playing Whether the video is playing. */ - (void)pictureInPictureController:(nonnull AVPictureInPictureController *)pictureInPictureController setPlaying:(BOOL)playing { if (!playing){ [self.player pause]; self.isPipPaused = YES; } else { // Recommendation: If the PiP playback is complete and needs to be replayed, you can additionally execute the code in the following if statement. if (self.currentPlayerStatus == AVPStatusCompletion) { [self.player seekToTime:0 seekMode:AVP_SEEKMODE_ACCURATE]; } [self.player start]; self.isPipPaused = NO; } [pictureInPictureController invalidatePlaybackState]; }
In-app Picture-in-Picture
When you use the PiP feature, it is an out-of-app PiP by default. To implement in-app PiP, you can first use the following API operation to determine whether the PiP feature is enabled:
/**
@brief Indicates whether PiP is enabled.
@param pictureInPictureController The PiP controller.
@param isEnable Whether PiP is enabled.
*/
- (void)pictureInPictureControllerIsPictureInPictureEnable:(nullable AVPictureInPictureController *)pictureInPictureController isEnable:(BOOL)isEnable;When the PiP feature is enabled, you can disable the automatic start of PiP and manually control the feature's activation. The following code provides an example:
- (void) pictureInPictureControllerIsPictureInPictureEnable:(nullable AVPictureInPictureController *) pictureInPictureController isEnable:(BOOL) isEnable
{
if (isEnable && pictureInPictureController) {
_pipController = pictureInPictureController;
// close pip auto start
if (@available(iOS 15.0, *)) {
_pipController.canStartPictureInPictureAutomaticallyFromInline = false;
}
} else {
_pipController = NULL;
}
}
- (void) switchPip:(bool) enable {
if (_pipController == nil) {
return;
}
if (enable) {
// start pip
[_pipController startPictureInPicture];
} else {
// close pip
[_pipController stopPictureInPicture];
}
}RTS live streaming fallback
For detailed code examples, see the RTS Live Stream (RtsLiveStream) module in API-Example. This project is an Objective-C-based sample project for ApsaraVideo Player SDK for iOS that helps developers quickly integrate core SDK features.
For more information, see RTS live streaming.
Switch between left and right sound channels
The ApsaraVideo Player SDK for iOS uses the outputAudioChannel property to set the output audio channel. You can switch to the left or right channel if the input source is dual-channel. The setting has no effect if the input source is single-channel.
The output sound channel setting affects both audio rendering and PCM data callbacks.
// Set the AVPOutputAudioChannel enumeration value to switch the sound channel.
// AVP_AUDIO_CHANNEL_NONE: Do not specify a sound channel. Play with the input source's sound channel. This is the default value.
// AVP_AUDIO_CHANNEL_LEFT: Switch to the left sound channel for playback.
// AVP_AUDIO_CHANNEL_RIGHT: Switch to the right sound channel for playback.
self.player.outputAudioChannel = AVP_AUDIO_CHANNEL_NONE;Set the video background color
ApsaraVideo Player SDK for iOS lets you set the background color for player rendering. The following section shows the API operation and usage instructions:
API example
/**
@brief Set the video background color.
@param color the color
*/
-(void) setVideoBackgroundColor:(UIColor *)color;Usage instructions
// The parameter is 8-bit hexadecimal data. The 8-bit data is divided into groups of two, representing A (alpha transparency), R (red), G (green), and B (blue) in order.
// For example, 0x0000ff00 represents green.
[self.player setVideoBackgroundColor:0x0000ff00]Specify a playback domain name for VidAuth
Using the VidAuth method, you can specify fields such as the domain name that corresponds to the VID. For details on supported fields, see GetPlayInfo request parameters. The following section shows the API operation and usage instructions:
API example
/**
@brief Play using VID + PlayAuth. For more information, see https://www.alibabacloud.com/help/en/vod/user-guide/use-playback-credentials-to-play-videos
@param source The input type of AVPVidAuthSource.
@see AVPVidAuthSource
*/
- (void)setAuthSource:(AVPVidAuthSource*)source;Usage instructions
You can add the playDomain field through the addVidPlayerConfigByStringValue of the VidPlayerConfigGenerator interface.
VidPlayerConfigGenerator* gen = [[VidPlayerConfigGenerator alloc]init];
// Add the playDomain field. For fields that can be added, see
// https://www.alibabacloud.com/help/en/vod/developer-reference/api-vod-2017-03-21-getplayinfo
[gen addVidPlayerConfigByStringValue:@"playDomain" value: @"com.xxx.xxx"];
[source setPlayConfig:[gen generatePlayerConfig]];
[self.player setAuthSource:source]:Background decoding
Starting from V6.12.0, ApsaraVideo Player SDK supports background decoding. When this feature is enabled, the player can still decode and play video streams and trigger callbacks when it is in the background. The following code provides a usage example:
// A value of 1 enables background decoding. A value of 0 disables background decoding. The default value is 0.
[self.player setOption:ALLOW_DECODE_BACKGROUND valueInt:1];H.266 decoding plugin
H.266, also known as Versatile Video Coding (VVC), is a new-generation video encoding standard that can significantly save bitrate while maintaining the same image quality. To optimize performance and control the size of the main SDK, the H.266 value-added decoding capability is independently packaged as a plugin that supports on-demand integration.
Prerequisites
The ApsaraVideo Player SDK or All-in-One SDK is V7.6.0 or later.
You have obtained a Professional Edition license. For more information, see Obtain a license for ApsaraVideo Player SDK.
ApsaraVideo Player with the H.266 decoding plugin supports playing only H.266 videos that are transcoded by Alibaba Cloud Transcoding.
Integrate the plugin
Activate the plugin
Starting from ApsaraVideo Player SDK for iOS V7.7.0, the plugin is enabled by default and does not need to be manually activated.
[AliPlayerGlobalSettings enableCodecPlugin:@"vvc" valid:true];Related error codes
For more information about error codes related to the H.266 decoding plugin, see Common FAQ for players on different clients.
Auto-refresh the playback source
Enabling the auto-refresh feature for the playback source prevents playback interruptions that are caused by expiration under a signing mechanism. This feature triggers a listener to obtain a new address when the source becomes invalid. This ensures continuous and smooth video playback.
Prerequisites
The ApsaraVideo Player SDK or All-in-One SDK is V7.9.0 or later.
You are using a VidAuth source for playback or your service has configured URL signing.
VidAuth source
API example
/**
@brief Set the callback for VidAuth source expiration notification.
This method is triggered when the player detects that the current VidAuth source has expired.
You can refresh the VidAuth source within the callback and use the `callback` to return the updated VidAuth source,
ensuring uninterrupted and smooth video playback.
@param callback The callback block triggered when the VidAuth source expires.
Use this callback to provide a valid `VidAuth` object to update the player.
*/
-(void)setOnVidAuthExpiredCallback:(void (^)(id expiredSource, id<AVPSourceRefreshCallback> callback))callback;Component description
Usage instructions
You can obtain an audio or video playback credential by calling the GetVideoPlayAuth API operation. We recommend that you integrate the ApsaraVideo VOD server-side SDK to obtain credentials to avoid self-signing. For more information, see OpenAPI Portal.
[self.player setOnVidAuthExpiredCallback:^(id expiredSource, id<AVPSourceRefreshCallback> callback) {
// Get AVPVidAuthSource
if ([expiredSource isKindOfClass:[AVPVidAuthSource class]]) {
// ------------------- Start of user implementation -------------------
// Call your self-implemented function that obtains a new PlayAuth from your app server.
// clinetGetPlayAuthFunction is an example function name. Replace it with your own implementation.
[self clinetGetPlayAuthFunction:vid success:^(NSString* newPlayAuth){
// 1. Callback for successfully obtaining a new credential.
[vidAuth setPlayAuth:newPlayAuth];
// 2. Pass the updated object back to the player through the SDK's callback.
[callback onSuccess:vidAuth];
} failure:^(NSString* errorMsg) {
// Callback for failing to obtain a new credential.
// errorMsg contains detailed error information.
[callback onError:errorMsg];
}];
// ------------------- End of user implementation -------------------
}
}];UrlSource source
API example
/**
@brief Set the callback for URL source expiration notification.
This method is triggered when the player detects that the current URL source has expired.
You can refresh the URL source within the callback and use the `callback` to return the updated URL source,
ensuring uninterrupted video playback.
@note For information about configuring the URL signing mechanism, see the official Alibaba Cloud documentation:
https://www.alibabacloud.com/help/zh/vod/user-guide/configure-url-signing?spm=a2c4g.11186623.0.0.560c4140fGh8MW
@param callback The callback block triggered when the URL source expires.
Use this callback to provide a valid `URLSource` object to update the player.
*/
-(void)setOnURLSourceExpiredCallback:(void (^)(id expiredSource, id<AVPSourceRefreshCallback> callback))callback;Component description
Usage instructions
[self.player setOnURLSourceExpiredCallback:^(id expiredSource, id<AVPSourceRefreshCallback> callback) {
// Get AVPUrlSource
if ([expiredSource isKindOfClass:[AVPUrlSource class]]) {
AVPUrlSource *expiredUrlSource = (AVPUrlSource *)expiredSource;
NSString *expiredUrl = [expiredUrlSource.playerUrl absoluteString];
// Check if it contains auth_key
if (![expiredUrl containsString:@"auth_key="]) {
return;
}
// 1. Extract the original URL from the expired URL
NSRange authKeyQuestionRange = [expiredUrl rangeOfString:@"?auth_key="];
NSRange authKeyAmpersandRange = [expiredUrl rangeOfString:@"&auth_key="];
NSInteger authKeyIndex = NSNotFound;
if (authKeyQuestionRange.location != NSNotFound) {
authKeyIndex = authKeyQuestionRange.location;
} else if (authKeyAmpersandRange.location != NSNotFound) {
authKeyIndex = authKeyAmpersandRange.location;
}
NSString *originalUrl = nil;
if (authKeyIndex != NSNotFound) {
originalUrl = [expiredUrl substringToIndex:authKeyIndex];
} else {
// If auth_key is not found, assume the entire URL is the original URL
originalUrl = expiredUrl;
}
// 2. Prepare new signing parameters: authKey and expiration time
// If the class member authKey is valid, use authKey
NSString *key = (self.authKey.length > 0) ? self.authKey : @"";
if (!NOT_EMPTY(key)) {
[callback onError:@"REFRESH_ERROR:key fail"];
return;
}
// If the class member validTime is valid, use validTime; otherwise, use the default value
NSTimeInterval validTime = (self.validTime > 0) ? self.validTime : 3600; // Default is 3600 seconds
NSTimeInterval newExpireTime = [[NSDate date] timeIntervalSince1970] + validTime;
// 3. Use CdnAuthUtil to generate a new signed URL (Type A)
NSString *newAuthUrl = [CdnAuthUtil aAuthWithUri:originalUrl key:key exp:newExpireTime];
AVPUrlSource *resultSource = [[AVPUrlSource alloc] urlWithString:newAuthUrl];
// 4. Handle the callback
if (newAuthUrl) {
[callback onSuccess:resultSource];
} else {
[callback onError:@"REFRESH_ERROR:refresh fail"];
}
}
}];Supplementary utility functions
This example uses type A signing.
Performance
Set the playback scenario
Setting a playback scenario automatically configures optimal parameters, such as buffer settings and feature toggles, based on the scenario. This setting is also compatible with custom parameter settings that are configured using the setConfig interface. Custom settings take precedence.
After you set the playback scenario, you can use the
getConfiginterface to view the parameter settings.
API example
/**
@brief Set player scene.
@param scene Player scene.
@see AVPScene
*/
-(void) setPlayerScene:(AVPScene)scene;Playback scenarios
typedef enum _AVPScene {
/**
* Scene: None
*/
SceneNone,
/**
* Long video scene: applicable to videos longer than 30 minutes
*/
SceneLong,
/**
* Medium video scene: applicable to videos between 5 and 30 minutes
*/
SceneMedium,
/**
* Short video scene: applicable to videos between 0 seconds and 5 minutes
*/
SceneShort,
/**
* Live streaming scene
*/
SceneLive,
/**
* RTS live scene
*/
SceneRTSLive
} AVPScene;Usage instructions
// Set the short video scene.
[self.player setPlayerScene:SceneShort];
// Set the medium video scene.
[self.player setPlayerScene:SceneMedium];
// Set the long video scene.
[self.player setPlayerScene:SceneLong];
// Set the live streaming scene.
[self.player setPlayerScene:SceneLive]; Pre-rendering
ApsaraVideo Player SDK for iOS supports fast rendering of the first frame before playback starts, which can improve the first frame loading speed.
This feature is disabled by default.
After this feature is enabled, it affects the trigger order of the preparation success and first frame rendering events. If the feature is disabled, the preparation success event is called back before the first frame rendering event. If the feature is enabled, the first frame rendering may be triggered before the preparation success event due to different decoding and rendering speeds. However, this does not affect playback.
The following code provides an example:
[self.player setOption:ALLOW_PRE_RENDER valueInt:1];Local caching
For detailed code examples, see the Video Preload (PreloadUrl) module in API-Example. This project is an Objective-C-based sample project for ApsaraVideo Player SDK for iOS that helps developers quickly integrate core SDK features.
ApsaraVideo Player SDK for iOS provides a local caching feature. This feature improves the first frame loading speed, seek speed, and reduces stuttering when users play a video repeatedly. It also helps save traffic.
Enable local caching
By default, the local caching feature is disabled. To use this feature, you must manually enable it. You can control this feature using AliPlayerGlobalSettings in enableLocalCache. The following is an example:
/**
* Enable local caching. After enabling, videos will be cached to local files.
* @param enable: Local caching feature switch. true: enable, false: disable. Default is false.
* @param maxBufferMemoryKB: Deprecated since V5.4.7.1, has no effect.
* @param localCacheDir: Must be set. The directory for local cache files, must be an absolute path.
*/
[AliPlayerGlobalSettings enableLocalCache:true maxBufferMemoryKB:1024 localCacheDir:@""];
/**
@brief Settings for automatic clearing of local cache files.
@param expireMin: Deprecated since V5.4.7.1, has no effect.
@param maxCapacityMB: Maximum cache capacity in megabytes. Default is 20 GB. During cleanup, if the total cache capacity exceeds this size, the oldest cache files will be deleted one by one, sorted by the last access time of the cache item, until the total capacity is less than or equal to the maximum capacity.
@param freeStorageMB: Minimum free disk space in megabytes. Default is 0. During cleanup, similar to maximum cache capacity, if the current disk space is less than this value, cache files will also be deleted one by one according to the rule until the free storage is greater than or equal to this value or all caches are cleared.
*/
[AliPlayerGlobalSettings setCacheFileClearConfig:0 maxCapacityMB:0 freeStorageMB:0];
/**
* Callback to get the hash value of the loaded URL, used as a unique ID for the URL. It must be ensured that each URL is unique.
*/
// You need to implement this function yourself and pass the function pointer to setCacheUrlHashCallback.
static NSString *CaheUrlHashHandle(NSString *url) {
return @"xxx";
}
[AliPlayerGlobalSettings setCacheUrlHashCallback:&CaheUrlHashHandle];If a video playback URL contains signing parameters that change, you can remove the signing parameters from the URL before you call the
setCacheUrlHashCallbackinterface to calculate a hash value, such as an MD5 hash. This improves the cache hit ratio for the same URL with different signing parameters. For example, if the playback URL with signing parameters ishttp://****.mp4?aaa, usehttp://****.mp4to calculate the hash value. However, if the video is an encrypted M3U8 video, removing the signing parameters from its key URL before calculating the hash value may cause different videos to hit the same key in the cache, which results in playback failure. Solution: In the callback ofsetCacheUrlHashCallback, you can check the domain name and remove the signing parameters only for the playback domain (http(s)://xxxxx.m3u8?aaaa). Do not remove the signing parameters for the key URL domain (http(s)://yyyyy?bbbb).
If the server supports both HTTP and HTTPS protocols, but the different protocols point to the same media file, you can remove or unify the request header before you calculate the MD5 value. For example:
If the video playback URLs are
https://****.mp4andhttp://****.mp4, you can use****.mp4to calculate the MD5 value during loading.If the video playback URL is
https://****.mp4, you can unify it tohttp://****.mp4before you calculate the MD5 value during loading.
For ApsaraVideo Player SDK V5.5.4.0 and later, if the video playback URL has signing parameters and the playback protocol is HLS, you can set the
AVPConfig.enableStrictAuthModefield to select different signing modes. The default value is false for versions 5.5.4.0 to 6.21.0. The default value is true for versions 7.0.0 and later.Non-strict signing (false): Signing is also cached. If only part of the media was cached last time, the player uses the cached signing to initiate a request when playing the non-cached part next time. If the validity period of the URL signing is very short, this causes playback exceptions.
Strict signing (true): Signing is not cached. Signing is performed every time playback starts. This causes playback to fail without a network connection.
Enable or disable local caching for a single URL
If you want to disable local caching for a single URL, you can set it in the player config. The following code provides an example:
// First, get the configuration.
AVPConfig *config = [self.player getConfig];
// Whether to enable local caching for the playback URL. The default value is true. When local caching is enabled in AliPlayerGlobalSettings, and local caching is also enabled here (set to true), local caching for this URL will take effect. If set to false here, local caching for this URL is disabled.
config.enableLocalCache = false;
....// Other settings.
// Set the configuration for the player.
[self.player setConfig:config];Use the default cache path
If you want to use the default path for caching, you can make the following setting through AliPlayerGlobalSettings.
[AliPlayerGlobalSettings enableLocalCache:true];Preloading
ApsaraVideo Player SDK for iOS provides a preloading feature, which is an upgrade to the local caching feature. By setting the memory size that is occupied by the video cache, you can further improve the first frame loading speed of the video.
The limits of the preloading feature are as follows:
It currently supports loading single media files such as MP4, MP3, FLV, and HLS.
By default, ApsaraVideo Player SDK for iOS provides an automatic scheduling capability for network resources during preloading. This is to reduce the impact of preloading network requests on the network requests of the video that is being played. The automatic scheduling policy is that preloading is allowed to make requests only after the buffer of the video that is being played reaches a certain threshold. To control real-time requests for preloading, you can disable this policy using the following method:
[AliPlayerGlobalSettings enableNetworkBalance:false];Enable the local caching feature. For more information, see Local caching.
Set the data source.
VidAuth (recommended)
AVPVidAuthSource* vidAuthSource = [[AVPVidAuthSource alloc] init]; [vidAuthSource setVid:@"Vid information"]; // Required. The video ID. [vidAuthSource setPlayAuth:@"<yourPlayAuth>"]; // Required. The playback credential. You need to call the GetVideoPlayAuth API operation of ApsaraVideo VOD to generate it. [vidAuthSource setRegion:@"Access region"]; // For player SDKs V5.5.5.0 and later, this parameter is deprecated. You do not need to set the region; the player will automatically parse it. For player SDKs earlier than V5.5.5.0, this parameter is required. The access region of ApsaraVideo VOD, default is cn-shanghai. [vidAuthSource setQuality:@"Selected definition"]; // "AUTO" represents adaptive bitrate.VidSts
AVPVidStsSource* vidStsSource = [[AVPVidStsSource alloc] init]; [vidStsSource setVid: @"Vid information"]; // Required. The video ID. [vidStsSource setRegion:@"Access region"]; // Required. The access region of ApsaraVideo VOD, default is cn-shanghai. [vidStsSource setSecurityToken: @"<yourSecurityToken>"]; // Required. The STS token. You need to call the AssumeRole API operation of STS to generate it. [vidStsSource setAccessKeySecret: @"<yourAccessKeySecret>"]; // Required. The AccessKey secret of the temporary STS AccessKey pair. You need to call the AssumeRole API operation of STS to generate it. [vidStsSource setAccessKeyId: @"<yourAccessKeyId>"]; // Required. The AccessKey ID of the temporary STS AccessKey pair. You need to call the AssumeRole API operation of STS to generate it. [vidStsSource setQuality:@"Selected definition"]; // "AUTO" represents adaptive bitrate.UrlSource
NSString* url = @"Playback URL"; // Required. The playback URL, which can be a third-party VOD URL or a playback URL in ApsaraVideo VOD. AVPUrlSource* urlSource = [[AVPUrlSource alloc]urlWithString:url];Set task parameters.
NoteThis applies only to multi-bitrate videos. You can set only one of
setDefaultBandWidth,setDefaultResolution, orsetDefaultQuality.AVPPreloadConfig *config = [[AVPPreloadConfig alloc]init]; // Set the preload bitrate for multi-bitrate streams. [config setDefaultBandWidth:400000]; // Set the preload resolution for multi-bitrate streams. [config setDefaultResolution:640 * 480]; // Set the preload quality for multi-bitrate streams. [config setDefaultQuality:@"FD"]; // Set the preload duration. [config setDuration:1000];Add a task listener.
Build a task and add it to the
MediaLoaderV2instance to start preloading.VidAuth (recommended)
// Build the preload task. AVPPreloadTask* mPreloadTask = [[AVPPreloadTask alloc]initWithVidAuthSource:vidAuthSource preloadConfig:config]; // Get the MediaLoaderV2 instance. AliMediaLoaderV2* vodMedialoader = [AliMediaLoaderV2 shareInstance]; // Add the task and start preloading. NSString* taskId = [vodMedialoader addTask:mPreloadTask listener:self];VidSts
// Build the preload task. AVPPreloadTask* mPreloadTask = [[AVPPreloadTask alloc]initWithVidStsSource:vidStsSource preloadConfig:config]; // Get the MediaLoaderV2 instance. AliMediaLoaderV2* vodMedialoader = [[AliMediaLoaderV2 alloc]init]; // Add the task and start preloading. NSString* taskId = [vodMedialoader addTask:mPreloadTask listener:self];UrlSource
// Build the preload task. AVPPreloadTask* mPreloadTask = [[AVPPreloadTask alloc]initWithUrlSource:urlSource preloadConfig:config]; // Get the MediaLoaderV2 instance. AliMediaLoaderV2* vodMedialoader = [[AliMediaLoaderV2 alloc]init]; // Add the task and start preloading. NSString* taskId = [vodMedialoader addTask:mPreloadTask listener:self];Optional: Manage tasks.
[vodMedialoader cancelTask:taskId]; // Cancel the preload task with the specified task ID. [vodMedialoader pauseTask:taskId]; // Pause the preload task with the specified task ID. [vodMedialoader resumeTask:taskId]; // Resume the preload task with the specified task ID.Optional: Delete loaded files.
You can delete loaded files as needed to save space. ApsaraVideo Player SDK for iOS does not provide a deletion interface. You need to delete the files in the loading directory in the app.
Dynamic preloading
The dynamic preloading policy allows integrators to control both the cache of the currently playing video and the number and cache of preloaded videos, balancing the playback experience with cost overhead for business needs.
Preload multi-bitrate HLS videos
In listPlayer and multi-bitrate HLS video playback scenarios, you can preload a stream with a definition that matches the current playback definition and select a preload mode as needed.
Get the download speed
You can obtain the download speed of the currently playing video. You can obtain the speed in the onCurrentDownloadSpeed callback. The following code provides an example:
- (void)onCurrentDownloadSpeed:(AliPlayer *)player speed:(int64_t)speed{
intspeed_=speed;
}Network features
HTTPDNS
HTTPDNS sends DNS resolution requests to a specific HTTPDNS server to obtain faster and more stable domain name resolution results. This reduces the risk of DNS hijacking.
ApsaraVideo Player SDK provides an enhanced HTTPDNS feature that offers HTTPDNS services specifically for Alibaba Cloud CDN domain names. This feature supports precise scheduling and real-time resolution for Alibaba Cloud CDN, which effectively improves network performance.
Enhanced HTTPDNS usage example
The enhanced HTTPDNS feature is available only for accelerated domain names. Make sure that the domain name you configure is an accelerated domain name that is fully configured and operational. To add and configure an accelerated domain name in ApsaraVideo VOD, see Add an accelerated domain name. For more information about accelerated domain names, see Alibaba Cloud CDN.
// Enable enhanced HTTPDNS.
[AliPlayerGlobalSettings enableEnhancedHttpDns:YES];
// Optional: Add a domain name for HTTPDNS pre-resolution.
[[AliDomainProcessor shareInstance] addPreResolveDomain:@"player.***alicdn.com"];HTTP/2
Starting from V5.5.0.0, ApsaraVideo Player SDK for iOS enables HTTP/2 by default.
ApsaraVideo Player SDK for iOS supports the HTTP/2 protocol. This protocol uses multiplexing to avoid head-of-line blocking and improve playback performance. The following code provides an example:
[AliPlayerGlobalSettings setUseHttp2:true];Pre-establish TCP connections for HTTP
For HTTP video playback requests (not HTTPS), pre-establishing a TCP connection can significantly improve the user experience, reduce network connection time, ensure immediate and continuous playback, and optimize the use of network and system resources. The usage is as follows:
// The domain format is host[:port], where port is optional. Multiple domain names are separated by semicolons (;).
// Global settings
// The full interface uses the current string each time it is set (more - add, less - delete). An empty string stops pre-connection.
[AliPlayerGlobalSettings setOption:SET_PRE_CONNECT_DOMAIN value: @"domain1;domain2"];Video download
For detailed code examples, see the Video Download and Offline Playback (Download) module in API-Example. This project is an Objective-C-based sample project for ApsaraVideo Player SDK for iOS that helps developers quickly integrate core SDK features.
ApsaraVideo Player SDK for iOS provides a video download feature for ApsaraVideo VOD. This feature allows users to cache videos locally for viewing with ApsaraVideo Player. The SDK offers two download methods: standard download and secure download.
Standard download: The downloaded video data is not encrypted by Alibaba Cloud. Users can play it with third-party players.
Secure download: The downloaded video data is encrypted by Alibaba Cloud. Third-party players cannot play the data. The data can be played only using ApsaraVideo Player.
Usage notes
The video download feature is supported only for VidSts and VidAuth methods.
To use the video download feature of the player, you need to enable and configure the download mode in the ApsaraVideo VOD console. For more information, see Offline download.
Video download supports resumable downloads.
Procedure
Optional: Configure the encryption verification file for secure download. This is required only for secure download, not for standard download.
NoteMake sure that the configured encryption verification file is consistent with the app information. Otherwise, the video download fails.
If you set the download method to secure download, you must configure the key file that is generated in the ApsaraVideo VOD console into the player SDK for decryption and verification during video download and playback. For more information about how to generate the key file, see Enable secure download.
We recommend that you configure the key file once in the Application. The following code provides an example:
NSString *encrptyFilePath = [[NSBundle mainBundle] pathForResource:@"encryptedApp" ofType:@"dat"]; [AliPrivateService initKey:encrptyFilePath];Create and set up the downloader.
The following code provides an example:
AliMediaDownloader *downloader = [[AliMediaDownloader alloc] init]; [downloader setSaveDirectory:self.downLoadPath]; [downloader setDelegate:self];Set event listeners.
The downloader provides multiple event listeners. The following code provides an example:
-(void)onPrepared:(AliMediaDownloader *)downloader mediaInfo:(AVPMediaInfo *)info { // The download item is successfully prepared. } -(void)onError:(AliMediaDownloader *)downloader errorModel:(AVPErrorModel *)errorModel { // A download error occurred. } -(void)onDownloadingProgress:(AliMediaDownloader *)downloader percentage:(int)percent { // Download progress percentage. } -(void)onProcessingProgress:(AliMediaDownloader *)downloader percentage:(int)percent { // Processing progress percentage. } -(void)onCompletion:(AliMediaDownloader *)downloader { // The download is successful. }Prepare the download source.
You can use the
preparemethod to prepare the download source. Both VidSts and VidAuth methods are supported. The following code provides an example:VidSts
// Create VidSts. AVPVidStsSource* stsSource = [[AVPVidStsSource alloc] init]; stsSource.region = @"Access region"; // The access region of ApsaraVideo VOD. Default is cn-shanghai. stsSource.vid = @"Vid information"; // The video ID. stsSource.securityToken = @"<yourSecurityToken>"; // The STS token. You need to call the AssumeRole API operation of STS to generate it. stsSource.accessKeySecret = @"<yourAccessKeySecret>"; // The AccessKey secret of the temporary STS AccessKey pair. You need to call the AssumeRole API operation of STS to generate it. stsSource.accessKeyId = @"<yourAccessKeyId>"; // The AccessKey ID of the temporary STS AccessKey pair. You need to call the AssumeRole API operation of STS to generate it. // If you have enabled HLS standard encryption parameter pass-through in the VOD console, and the default parameter name is MtsHlsUriToken, you need to set the config and pass it into the vid, as shown below. // If you have not enabled HLS standard encryption parameter pass-through in the VOD console, you do not need to integrate the following code. VidPlayerConfigGenerator* vp = [[VidPlayerConfigGenerator alloc] init]; [vp setHlsUriToken:yourMtsHlsUriToken]; stsSource.playConfig = [vp generatePlayerConfig]; // Prepare the download source. [downloader prepareWithVid:stsSource];VidAuth
// Create VidAuth. AVPVidAuthSource *authSource = [[AVPVidAuthSource alloc] init]; authSource.vid = @"Vid information"; // The video ID. authSource.playAuth = @"<yourPlayAuth>"; // The playback credential. You need to call the GetVideoPlayAuth API operation of ApsaraVideo VOD to generate it. authSource.region = @"Access region"; // For player SDKs V5.5.5.0 and later, this parameter is deprecated. You do not need to set the region; the player will automatically parse it. For player SDKs earlier than V5.5.5.0, this parameter is required. The access region of ApsaraVideo VOD, default is cn-shanghai. // If you have enabled HLS standard encryption parameter pass-through in the VOD console, and the default parameter name is MtsHlsUriToken, you need to set the config and pass it into the vid, as shown below. // If you have not enabled HLS standard encryption parameter pass-through in the VOD console, you do not need to integrate the following code. VidPlayerConfigGenerator* vp = [[VidPlayerConfigGenerator alloc] init]; [vp setHlsUriToken:yourMtsHlsUriToken]; authSource.playConfig = [vp generatePlayerConfig]; // Prepare the download source. [downloader prepareWithVid:authSource];
NoteIf you have enabled HLS standard encryption parameter pass-through in the VOD console, and the default parameter name is MtsHIsUriToken (for more information, see HLS standard encryption parameter pass-through), please set the MtsHIsUriToken value into the VOD source as shown in the code above.
After successful preparation, select a download item.
After the preparation is successful, the
onPreparedmethod is called back. The returned TrackInfo contains information such as the definition of each video stream. You can select a track to download. The following code provides an example:-(void)onPrepared:(AliMediaDownloader *)downloader mediaInfo:(AVPMediaInfo *)info { NSArray<AVPTrackInfo*>* tracks = info.tracks; // For example, download the first TrackInfo. [downloader selectTrack:[tracks objectAtIndex:0].trackIndex]; }Update the download source and start the download.
To prevent VidSts and VidAuth from expiring, we recommend that you update the download source information before you start the download. The following code provides an example:
// Update the download source. [downloader updateWithVid:vidSource] // Start the download. [downloader start];After the download succeeds or fails, release the downloader.
After the download is successful, you can call
destroyto release the downloader.[self.downloader destroy]; self.downloader = nil;
Encrypted video playback
ApsaraVideo VOD supports HLS encryption, Alibaba Cloud proprietary cryptography, and DRM encryption. Live streaming videos support only DRM encryption. For more information about encrypted playback, see Encrypted video playback.
Native RTS playback
ApsaraVideo Player SDK for iOS integrates the Native RTS SDK to implement the native low-latency live streaming feature. For more information, see Implement RTS stream pulling on iOS.