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.

  1. 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. traceId is the unique identifier of the device or user. Generally, tranceId is set to the value of imei or idfa. 
    [play setTraceID:@"xxxxxx"];
  2. Configure listeners.
    You can configure multiple listeners for your player.
    • You must configure the prepare callback because you need to call the start method in the prepare callback to start manual playback.
    • We recommend that you configure the onPlayerEvent and onError 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 track 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 track The callback that indicates 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.
    }
  3. 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 stream playback.
    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 Region IDs of ApsaraVideo VOD.
    • 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.

    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 credential for media playback. 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.

    We recommend that you use VidAuth for video playback in ApsaraVideo VOD. Compared with STS-based playback, 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 in which ApsaraVideo VOD is activated.
        source.vid = self."Vid"; // The ID of the video.
        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 temporary 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 = @"Authentication"; // The authentication 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.

    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.

  4. Configure the view.
    If the playback source contains video images, you must configure the view to display the video images in the player. The following sample code provides an example:
    self.player.playerView = self.avpPlayerView.playerView;// The displayed view.
  5. Optional:Enable the autoplay feature. By default, this feature is disabled.
    self.player.autoPlay = YES;
  6. Prepare the player.
    Call the [self.player prepare] method to read and parse data.
    [self.player prepare];
  7. 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.
    Notice When a video is automatically played, the AVPEventAutoPlayStart callback is returned instead of the AVPEventPrepareDone 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 playback

You can call the start method to start the playback. The following sample code provides an example:
 [self.player start];

Play a video from a specified point in time

You can call the 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. The following sample code provides an example:
// The position parameter specifies the point in time when playback starts. Unit: milliseconds. Only the AVP_SEEKMODE_INACCURATE seek mode is supported. 
[self.player seekToTime:position seekMode:AVP_SEEKMODE_INACCURATE];

Pause playback

You can call the pause method to pause the playback. The following sample code provides an example:
[self.player pause];

Stop playback

You can call the stop method to stop the playback. The following sample code provides an example:
[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

You can call the scalingMode method to scale in or scale out the video images without changing the original aspect ratio, or stretch the video images. The following sample code provides an example:
// 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

You can call the rotateMode method to specify a rotation angle for video images. The following sample code provides an example:
// 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

You can call the mirrorMode method to specify a mirroring mode. Horizontal mirroring, vertical mirroring, and no mirroring are supported. The following sample code provides an example:
// 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

You can query the current playback position in the onCurrentPositionUpdate callback. The following sample code provides an example:
- (void)onCurrentPositionUpdate:(AliPlayer*)player position:(int64_t)position {
// The position parameter indicates the current playback position. Unit: milliseconds.
NSString *position_ = position;
}

Obtain the video duration

You can query the total duration of a video. The video duration can be obtained only after the video is loaded. For example, you can query the video duration after the onPrepared callback is invoked. Unit: milliseconds. The following sample code provides an example:
-(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

You can query the current buffering position in the onBufferedPositionUpdate callback. The following sample code provides an example:
- (void)onBufferedPositionUpdate:(AliPlayer*)player position:(int64_t)position {
    NSString *bufferPosition = position;
}

Listen to the playback status

You can listen to the player status in the onPlayerStatusChanged callback. The following sample code provides an example:
- (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 player volume or configure the mute mode for the playback.

Change the volume

You can change the volume of a video to up to twice the original volume. Noise may occur if you set the volume to a value higher than 1. Call the volume method to change the volume. You can also obtain the current volume. The following sample code provides an example:
// 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

Call the muted method to mute a video during the playback. The following sample code provides an example:
self.player.muted = YES;

Configure the playback speed

ApsaraVideo Player SDK for iOS allows you call the 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. The following sample code provides an example:
// 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

ApsaraVideo Player SDK for iOS supports loop playback. Call the 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. The following sample code provides an example:
self.player.loop = YES;
The AVPEventLoopingStart callback is returned when loop playback starts. The following sample code provides an example:
- (void)onPlayerEvent:(AliPlayer*)player eventType:(AVPEventType)eventType {
    switch (eventType) {
        case AVPEventLoopingStart:
            break;
    }
}