This topic describes how to configure the basic features of ApsaraVideo Player SDK for iOS.
Create a player
This section describes how to use ApsaraVideo Player SDK for iOS to play videos. Manual playback and autoplay are supported.
- Create a player.
Create an ApsaraVideo player.
// Create a player. self.player = [[AliPlayer alloc] init]; // By default, event tracking logs are uploaded. Set tranceId to DisableAnalytics to disable this feature. If you set traceId to a value other than DisableAnalytics, the event tracking logs are uploaded. // We recommend that you specify traceId to facilitate log tracking. In most cases, the value is the International Mobile Equipment Identity (IMEI) or the Identifier for Advertisers (IDFA) of the device. [play setTraceID:@"xxxxxx"];
- Configure listeners.
You can configure multiple listeners for your player.
- You must configure the
prepare
callback because you need to call thestart
method in theprepare
callback to start manual playback. - We recommend that you configure the
onPlayerEvent
andonError
callbacks.
@interface SimplePlayerViewController ()<AVPDelegate> @end - (void)viewDidLoad { self.player = [[AliPlayer alloc] init]; self.player.playerView = self.avpPlayerView.playerView; self.player.delegate = self; //... } /** @brief The callback for an invalid delegate. @param player The pointer for the player. @param errorModel The description of player errors. For more information, see AliVcPlayerErrorModel. */ - (void)onError:(AliPlayer*)player errorModel:(AVPErrorModel *)errorModel { // Indicates that an error occurred and the playback is stopped. } /** @brief The callback for player events. @param player The pointer for the player. @param eventType The type of the player event. For more information, see AVPEventType. */ -(void)onPlayerEvent:(AliPlayer*)player eventType:(AVPEventType)eventType { switch (eventType) { case AVPEventPrepareDone: { // The preparation is complete. } break; case AVPEventAutoPlayStart: // The autoplay starts. break; case AVPEventFirstRenderedStart: // The first frame appears. break; case AVPEventCompletion: // The playback is complete. break; case AVPEventLoadingStart: // The buffering starts. break; case AVPEventLoadingEnd: // The buffering is complete. break; case AVPEventSeekEnd: // The seeking is complete. break; case AVPEventLoopingStart: // The loop playback starts. break; default: break; } } /** @brief The callback for the current playback position. @param player The pointer for the player. @param position The current playback position. */ - (void)onCurrentPositionUpdate:(AliPlayer*)player position:(int64_t)position { // Updates the playback progress. } /** @brief The callback for the buffer position. @param player The pointer for the player. @ param position The current buffer position. */ - (void)onBufferedPositionUpdate:(AliPlayer*)player position:(int64_t)position { // Updates the buffer progress. } /** @brief The callback for obtaining the track information. @param player The pointer for the player. @param info The array of track information. For more information, see AVPTrackInfo. */ - (void)onTrackReady:(AliPlayer*)player info:(NSArray<AVPTrackInfo*>*)info { // Obtains the information about different bitrates. } /** @brief The callback for displaying the subtitle. @param player The pointer for the player. @param index The index number for the subtitle. @param subtitle The string of the subtitle. */ - (void)onSubtitleShow:(AliPlayer*)player index:(int)index subtitle:(NSString *)subtitle { // Obtains the subtitle for display. } /** @brief The callback for hiding the subtitle. @param player The pointer for the player. @param index The index number for the subtitle. */ - (void)onSubtitleHide:(AliPlayer*)player index:(int)index { // Hides the subtitles. } /** @brief The callback for snapshot capture. @param player The pointer for the player. @param image The image. */ - (void)onCaptureScreen:(AliPlayer *)player image:(UIImage *)image { // Previews and saves the snapshot. } /** @brief The callback that indicates that the track is switched. @param player The pointer for the player. @param info The information about the switching after the switching is complete. For more information, see AVPTrackInfo. */ - (void)onTrackChanged:(AliPlayer*)player info:(AVPTrackInfo*)info { // Notifies the result of track switching. }
- You must configure the
- Configure a playback source.
- ApsaraVideo Player SDK for iOS supports video-on-demand (VOD) playback based on UrlSource, VidAuth, VidSts, and VidMps. Encrypted VOD playback is also supported. We recommend that you play videos based on VidAuth in ApsaraVideo VOD.
- ApsaraVideo Player SDK for iOS supports UrlSource-based and encrypted live streaming.
Note- UrlSource is used for URL-based playback, and VidAuth, VidSts, and VidMps are used for Vid-based playback. VidSts and VidAuth can be used for video playback only in ApsaraVideo VOD. VidMps can be used for video playback only in ApsaraVideo Media Processing (MPS).
- For more information about regions, see VOD centers and endpoints.
- For more information about video playback in MPS, see Play videos.
Play on-demand videos
If you play an on-demand video based on UrlSource, you must set the source of the player to the playback URL of the video. The playback URL is generated by ApsaraVideo VOD or a third-party service. You can call the GetPlayInfo operation to obtain a playback URL that is generated by ApsaraVideo VOD. We recommend that you use a server SDK to obtain media playback URLs in ApsaraVideo VOD. This frees you from complex signature calculations. For more information about the GetPlayInfo operation, see OpenAPI Explorer.
Sample code
AVPUrlSource *urlSource = [[AVPUrlSource alloc] urlWithString:url]; // The playback URL of the video. The URL is generated by ApsaraVideo VOD or a third-party service. [self.player setUrlSource:urlSource];
If you play an on-demand video based on VidAuth, you must set vid to the media ID and playAuth to the credential for media playback. You can call the SearchMedia operation to obtain the media ID. Alternatively, you can log on to the ApsaraVideo VOD console and choose Media Files > Audio/Video to view the media ID. You can call the GetVideoPlayAuth operation to obtain the playback credential. We recommend that you use a server SDK to obtain credentials for media playback in ApsaraVideo VOD. This frees you from complex signature calculations. For more information about the GetVideoPlayAuth operation, see OpenAPI Explorer.
We recommend that you use VidAuth for video playback in ApsaraVideo VOD. Compared with video playback based on Security Token Service (STS), VidAuth-based playback is easier to use and more secure. For more information about the comparison between the two playback methods, see Comparison between credentials and STS.
Sample code
AVPVidAuthSource *authSource = [[AVPVidAuthSource alloc] init]; authSource.vid = @"Vid"; authSource.playAuth = @"playAuth"; // The playback credential. authSource.region = @"Region"; // The ID of the region in which ApsaraVideo VOD is activated. Default value: cn-shanghai. [self.player setAuthSource:authSource];
If you play an on-demand video based on VidSts, a temporary STS token is used instead of a playback credential. In this case, you must obtain an STS token before you play videos on demand. For more information, see Create a role and grant temporary access permissions to the role by using STS. If you play an on-demand video based on VidSts, you must set securityToken to the temporary STS token and specify the temporary AccessKey pair.
Sample code
AVPVidStsSource *source = [[AVPVidStsSource alloc] init]; source.region = self."region"; // The ID of the region from which you want to access ApsaraVideo VOD. source.vid = self."Vid"; // The video ID. source.securityToken = self."<yourSecurityToken>"; // The STS token. source.accessKeySecret = self."<yourAccessKeySecret>"; // The AccessKey secret. source.accessKeyId = self."<yourAccessKeyId>"; // The AccessKey ID. // Configure the playback source. [self.player setStsSource:source]
ApsaraVideo Player SDK for iOS supports video playback based on VidMps in MPS. You must obtain the following information before you use VidMps for playback:
- vid: the ID of the media file in MPS.
- AcessKeyId and AccessKeySecret: the AccessKey pair that is generated when the temporary STS token is issued.
- SecurityToken: the STS token.
- domainRegion: the region in which the media file is stored.
- authInfo: the authorization information.
For more information, see Play videos.
Sample code
AVPVidMpsSource *mpsSource = [[AVPVidMpsSource alloc] init]; mpsSource.region = @"Region"; // The ID of the region in which ApsaraVideo VOD is activated. Default value: cn-shanghai. mpsSource.vid = @"Media ID"; // The ID of the video. mpsSource.accId = @"<yourAccessKeyId>"; // The AccessKey ID. mpsSource.accSecret = @"<yourAccessKeySecret>"; // The AccessKey secret. mpsSource.stsToken = @"<yourSecurityToken>"; // The STS token. mpsSource.authInfo = @"Authorization"; // The authorization information. mpsSource.playDomain = @"Playback domain"; // The domain name for playback. mpsSource.mtsHlsUriToken = @"HlsUriToken"; // The HlsUriToken. [self.player setMpsSource:mpsSource];
ApsaraVideo VOD supports HTTP-Live-Streaming (HLS) encryption, Alibaba Cloud proprietary cryptography, and digital rights management (DRM) encryption. For more information, see Play an encrypted video.
Play a live stream
If you play a live stream based on UrlSource, you must set the source of the player to the playback URL of the live stream. The streaming URL is generated by ApsaraVideo Live or a third-party service. You can generate a streaming URL for a live stream by using the URL generator in the ApsaraVideo Live console. For more information, see OpenAPI Explorer.
Sample code
AVPUrlSource *urlSource = [[AVPUrlSource alloc] urlWithString:url]; // The streaming URL. The URL is generated by ApsaraVideo Live or a third-party service. [self.player setUrlSource:urlSource];
For more information about how to play DRM-encrypted videos, see Play an encrypted video.
- Configure the view.
If the playback source contains video images, you must configure the view to display the video images in the player. Sample code:
self.player.playerView = self.avpPlayerView.playerView;// The displayed view.
- Optional:Enable the autoplay feature. By default, this feature is disabled.
self.player.autoPlay = YES;
- Prepare the player.
Call the
[self.player prepare]
method to read and parse data.[self.player prepare];
- Start the playback.
Call the
start
method to start video playback. If the autoplay feature is enabled, the video is automatically played after data is parsed.Important When a video is automatically played, theAVPEventAutoPlayStart
callback is returned instead of theAVPEventPrepareDone
callback.[self.player start];
Manage playback
ApsaraVideo Player SDK for iOS allows you to manage media playback. For example, you can start or pause the playback, or start the playback from a specific point in time.
Start the playback
start
method to start the playback. Sample code:
[self.player start];
Play a video from a specified point in time
seekToTime
method to play a video from a specified point in time. This feature is used when the user drags the slider on the progress bar or the video is resumed from a specific point in time. Sample code:
// Specify the time point from which you want to play the video for the position parameter. Unit: milliseconds. Use seekMode to specify the accurate seeking mode or the inaccurate seeking mode.
// Use the accurate seeking mode.
[self.player seekToTime:position seekMode:AVP_SEEKMODE_ACCURATE];
// Use the inaccurate seeking mode.
[self.player seekToTime:position seekMode:AVP_SEEKMODE_INACCURATE];
Pause playback
pause
method to pause the playback. Sample code:
[self.player pause];
Stop playback
stop
method to stop the playback. Sample code:
[self.player stop];
Set the video display mode
ApsaraVideo Player SDK for iOS allows you to configure display settings for playback. For example, you can specify how video images are scaled, rotated, or mirrored.
Scaling
scalingMode
method to scale in or scale out the video images without changing the original aspect ratio, or stretch the video images. Sample code:
// Scale in the video to fit the view. The aspect ratio of the video is maintained.
self.player.scalingMode = AVP_SCALINGMODE_SCALEASPECTFIT;
// Scale out the video to fill the view. The aspect ratio of the video is maintained.
self.player.scalingMode = AVP_SCALINGMODE_SCALEASPECTFILL;
// Stretch the video to fill the view. The aspect ratio of the video is not maintained. Image distortion may occur if the aspect ratios of the video and the view are different.
self.player.scalingMode = AVP_SCALINGMODE_SCALETOFILL;
Rotating
rotateMode
method to specify a rotation angle for video images. Sample code:
// Set the rotation angle to 0° in the clockwise direction.
self.player.rotateMode = AVP_ROTATE_0;
// Set the rotation angle to 90° in the clockwise direction.
self.player.rotateMode = AVP_ROTATE_90;
// Set the rotation angle to 180° in the clockwise direction.
self.player.rotateMode = AVP_ROTATE_180;
// Set the rotation angle to 270° in the clockwise direction.
self.player.rotateMode = AVP_ROTATE_270;
Mirroring
mirrorMode
method to specify a mirroring mode. Horizontal mirroring, vertical mirroring, and no mirroring are supported. Sample code:
// Specify no mirroring for the video images.
self.player.mirrorMode = AVP_MIRRORMODE_NONE;
// Specify horizontal mirroring for the video images.
self.player.mirrorMode = AVP_MIRRORMODE_HORIZONTAL;
// Specify vertical mirroring for the video images.
self.player.mirrorMode = AVP_MIRRORMODE_VERTICAL;
Obtain playback information
ApsaraVideo Player SDK for iOS allows you to obtain playback information, such as the current playback progress, video duration, and buffering progress.
Obtain current playback progress
- (void)onCurrentPositionUpdate:(AliPlayer*)player position:(int64_t)position {
// The position parameter indicates the current playback position. Unit: milliseconds.
NSString *position = [NSString stringWithFormat:@"%lld, position"];
}
Obtain the video duration
-(void)onPlayerEvent:(AliPlayer*)player eventType:(AVPEventType)eventType {
switch (eventType) {
case AVPEventPrepareDone: {
if (self.player.duration >= 0) {
NSString *duration = self.player.duration;
}
}
break;
default:
break;
}
}
Obtain the buffering progress
- (void)onBufferedPositionUpdate:(AliPlayer*)player position:(int64_t)position {
NSString *bufferPosition = position;
}
Obtain the rendering frame rate, audio and video bitrate, and network downlink bitrate in real time
// Obtain the current frame rate for video rendering. The returned data is of the FLOAT data type.
[self.player getOption:AVP_OPTION_RENDER_FPS]
// Obtain the current video bitrate. The returned data is of the FLOAT data type.
[self.player getOption:AVP_OPTION_VIDEO_BITRATE]
// Obtain the current audio bitrate. The returned data is of the FLOAT data type. Unit: bit/s.
[self.player getOption:AVP_OPTION_AUDIO_BITRATE]
// Obtain the current network downlink bitrate. The returned data is of the FLOAT data type. Unit: bit/s.
[self.player getOption:AVP_OPTION_DOWNLOAD_BITRATE]
Listen to the playback status
- (void)onPlayerStatusChanged:(AliPlayer*)player oldStatus:(AVPStatus)oldStatus newStatus:(AVPStatus)newStatus {
switch (newStatus) {
case AVPStatusIdle:{
// The player is idle.
}
break;
case AVPStatusInitialzed:{
// The player is initialized.
}
break;
case AVPStatusPrepared:{
// The player is prepared.
}
break;
case AVPStatusStarted:{
// The player is playing a media stream.
}
break;
case AVPStatusPaused:{
// The playback is paused.
}
break;
case AVPStatusStopped:{
// The playback is stopped.
}
break;
case AVPStatusCompletion:{
// The player has finished playing.
}
break;
case AVPStatusError:{
// An error occurs in the player.
}
break;
default:
break;
}
}
Configure the volume
You can adjust the volume or configure the mute mode for the playback.
Change the volume
volume
method to change the volume. You can also obtain the current volume. Sample code:
// Set the volume to a real number from 0 to 2.
self.player.volume = 1.0f;
// Obtain the volume information.
self.player.volume
Configure the mute mode
muted
method to mute a video during the playback. Sample code:
self.player.muted = YES;
Configure the playback speed
rate
method to change the playback speed. Playback speeds ranging from 0.5x to 5x are supported. The audio pitch remains unchanged at different speeds. Sample code:
// Playback speeds ranging from 0.5x to 5x are supported. Common playback speeds are multiples of 0.5x, such as 0.5x, 1x, and 1.5x.
self.player.rate = 1.0f;
Configure multi-definition settings
If you play a video based on VidAuth or VidSts, you do not need to configure multi-definition settings for the playback. ApsaraVideo Player SDK for iOS automatically obtains video definitions from ApsaraVideo VOD. The SDK allows you to obtain video definitions and switch between definitions. This feature is not supported for UrlSource-based playback.
Obtain video definitions
After the video is loaded, you can obtain the video definitions. You can obtain the video definitions from the trackBitrate parameter that is nested under the info parameter in the onTrackReady callback.
- (void)onTrackReady:(AliPlayer*)player info:(NSArray<AVPTrackInfo*>*)info {
for (int i=0; i<info.count; i++) {
AVPTrackInfo* track = [info objectAtIndex:i];
switch (track.trackType) {
case AVPTRACK_TYPE_VIDEO: {
int trackBitrate = track.trackBitrate;
}
break;
}
}
}
Switching between definitions
You can call the selectTrack
method to set TrackInfo to the index that corresponds to the definition in which you want to play the video.
[self.player selectTrack:index];
Send a notification about definition changes
The onTrackChanged callback is returned after the video definition is switched.
- (void)onTrackChanged:(AliPlayer*)player info:(AVPTrackInfo*)info {
// The video definition is switched.
}
Enable loop playback
loop
method to enable loop playback. The loop playback feature allows you to play a video again from the beginning after the video playback ends. Sample code:
self.player.loop = YES;
AVPEventLoopingStart
callback is returned when loop playback starts. Sample code:
- (void)onPlayerEvent:(AliPlayer*)player eventType:(AVPEventType)eventType {
switch (eventType) {
case AVPEventLoopingStart:
break;
}
}