This topic describes how to create a player instance and use basic features of ApsaraVideo Player SDK for iOS, such as setting the volume, performing video seeking, monitoring playback status, enabling loop playback, configuring the playback speed, and switching audio tracks.
Play a video
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 AliPlayer object.
NoteApsaraVideo VOD supports the playback quality monitoring and single-point tracing features based on the event tracking logs. You can use the playback quality monitoring feature to query statistics about overall playback quality and use the single-point tracing feature to locate the specific user or device, analyze the playback behavior, and identify the error in an efficient manner. For more information, see Playback quality monitoring and Single-point tracing.
You can configure the
setTraceId
parameter to use the features. The following content describes the configurations:If you leave the
setTraceId
parameter empty, the event tracking logs are automatically uploaded. You can use only the playback quality monitoring feature. By default, this parameter is left empty.If you specify the unique identifier of the device or the user for the
setTraceId
parameter, the event tracking logs are automatically uploaded. You can use the playback quality monitoring feature and the single-point tracing feature. For example, you can specify the user ID or device ID such as the International Mobile Equipment Identity (IMEI) or the Identifier for Advertisers (IDFA) for this parameter.If you specify
DisableAnalytics
for thesetTraceId
parameter, the event tracking logs are not uploaded. You cannot use the playback quality monitoring feature or the single-point tracing feature.
// Create a player. self.player = [[AliPlayer alloc] init]; // We recommend that you specify the traceId parameter. [play setTraceID:@"xxxxxx"];
NoteThe event tracking logs are uploaded to nodes in the China (shanghai) region. The Singapore region will be available soon.
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 of 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 stopped. } /** @brief The callback for player events. @param player The pointer of the player. @param eventType The type of the player event. For more information, see AVPEventType. */ -(void)onPlayerEvent:(AliPlayer*)playereventType:(AVPEventType)eventType{ switch(eventType){ caseAVPEventPrepareDone:{ // The player is prepared. // If you set autoPlay to NO for the player, we recommend that you call start in the AVPEventPrepareDone callback. [self.playerstart]; } 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 of 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 of the player. @ param position The current buffer position. */ - (void)onBufferedPositionUpdate:(AliPlayer*)player position:(int64_t)position { // Updates the buffering progress. } /** @ brief The callback for obtaining the track information. @param player The pointer of the player. @param info The array of track information. For more information, see AVPTrackInfo. */ - (void)onTrackReady:(AliPlayer*)player info:(NSArray<AVPTrackInfo*>*)info { // Obtains information about different bitrates. } /** @brief The callback for displaying the subtitle. @param player The pointer of the player. @param index The index number of 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 of the player. @param index The index number of the subtitle. */ - (void)onSubtitleHide:(AliPlayer*)player index:(int)index { // Hides the subtitle. } /** @brief The callback for snapshot capture. @param player The pointer of 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 of 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 { // Returns the result of track switching. }
Configure a playback source.
ApsaraVideo Player SDK for iOS supports video-on-demand (VOD) playback based on UrlSource, VidAuth, and VidSts. 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.
NoteUrlSource is used for URL-based playback, and VidSts and VidAuth are used for Vid-based playback.
For more information about regions, see Region IDs of ApsaraVideo VOD.
VOD playback
UrlSource-based playback
If you play an on-demand video based on UrlSource, set the source of the player to the playback URL of the video.
You can call the GetPlayInfo operation to obtain playback URLs in ApsaraVideo VOD. We recommend that you integrate ApsaraVideo VOD SDK to obtain media playback URLs in ApsaraVideo VOD. This frees you from complex signature calculations. For more information about the GetPlayInfo operation, visit OpenAPI Explorer.
Make sure that you are authorized to call API operations to obtain the full path of the local file if you want to play a local video. Example:
/sdcard/xxx/xxx/xxx.mp4
orcontent://xxx/xxx/xx.mp4
.
AVPUrlSource *urlSource = [[AVPUrlSource alloc] urlWithString:url]; // Required. The playback URL of the video. The URL can be generated by ApsaraVideo VOD or a third-party service. You can also use the path of a local video. [self.player setUrlSource:urlSource];
(Recommended) VidAuth-based playback
To use VidAuth for VOD playback, you must set the vid parameter to the ID of the audio or video file and set the playAuth parameter to the playback credential.
After you upload an audio or video file, you can log on to the ApsaraVideo VOD console and choose Media Files > Audio/Video to view the ID of the audio or video file. Alternatively, you can call the SearchMedia operation provided by the ApsaraVideo VOD SDK to obtain the ID.
You can call the GetVideoPlayAuth operation to obtain the playback credential. We recommend that you integrate ApsaraVideo VOD SDKs to obtain credentials for media playback. This frees you from complex signature calculations. For more information about the GetVideoPlayAuth operation, visit OpenAPI Explorer.
We recommend that ApsaraVideo VOD users use this method. 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.
AVPVidAuthSource *authSource = [[AVPVidAuthSource alloc] init]; authSource.vid = @"Vid"; // Required. The video ID. authSource.playAuth = @"<yourPlayAuth>"; // Required. The playback credential. To obtain a playback credential, call the GetVideoPlayAuth operation in ApsaraVideo VOD. authSource.region = @"Access region"; // This parameter is deprecated in ApsaraVideo Player SDK V5.5.5.0 or later. If you use ApsaraVideo Player SDK V5.5.5.0 or later, the player automatically parses the region information. If you use ApsaraVideo Player SDK V5.5.5.0 or earlier, this parameter is required. Specify the ID of the region in which ApsaraVideo VOD is activated for this parameter. Default value: cn-shanghai. // authSource.authTimeout=3600; // The validity period of the playback URL. Unit: seconds. Default value: 3600. If you have configured a validity period for signed URLs in the ApsaraVideo VOD console, the configuration of this parameter takes precedence. If you leave this parameter empty, the default value is used. The validity period must be longer than the actual duration of the video. Otherwise, the playback URL expires before the playback is complete. [self.player setAuthSource:authSource];
VidSts-based playback
If you use VidSts for VOD playback, a temporary STS token is used instead of a playback credential. In this case, you must obtain an STS token and AccessKey pair (AccessKey ID and AccessKey secret) before you play videos on demand. For more information about how to obtain an STS token, see Create a RAM role and grant temporary access permissions to the role by using STS.
AVPVidStsSource *source = [[AVPVidStsSource alloc] init]; source.vid = @"Vid"; // Required. The ID of the video. source.region = @"Access region"; // Required. The region in which ApsaraVideo VOD is activated. Default value: cn-shanghai. source.securityToken = @"<yourSecurityToken>"; // Required. The STS token. To generate an STS token, call the AssumeRole operation in STS. source.accessKeySecret = @"<yourAccessKeySecret>"; // Required. The AccessKey secret that is generated when the temporary STS token is issued. To generate the AccessKey secret, call the AssumeRole operation in STS. source.accessKeyId = @"<yourAccessKeyId>"; // Required. The AccessKey ID that is generated when the temporary STS token is issued. To generate the AccessKey ID, call the AssumeRole operation in STS. // source.authTimeout = 3600; // The validity period of the playback URL. Unit: seconds. Default value: 3600. If you have configured a validity period for signed URLs in the ApsaraVideo VOD console, the configuration of this parameter takes precedence. If you leave this parameter empty, the default value is used. The validity period must be longer than the actual duration of the video. Otherwise, the playback URL expires before the playback is complete. // Configure the playback source. [self.player setStsSource:source]
Encrypted playback
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.
Live streaming
UrlSource-based live streaming
If you play a live stream based on UrlSource, set the source of the player to the streaming URL of the live stream. The streaming URL can be a third-party streaming URL or a streaming URL that is generated in ApsaraVideo Live.
You can generate a source URL for a live stream by using the URL generator in the ApsaraVideo Live console. For more information, see URL generator.
AVPUrlSource *urlSource = [[AVPUrlSource alloc] urlWithString:url]; // Required. The streaming URL. The URL is generated by ApsaraVideo Live or a third-party service. [self.player setUrlSource:urlSource];
DRM-encrypted live streaming
For more information about DRM-encrypted live streaming, see Play an encrypted video.
Configure the view.
If the playback source contains video images, 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, the autoplay 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.ImportantWhen a video is automatically played, the
AVPEventAutoPlayStart
callback is invoked instead of theAVPEventPrepareDone
callback.[self.player start];
Control the 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
You can call the start
method to start the playback. Sample code:
[self.player start];
Start the playback from a specific point in time
You can call the seekToTime
operation 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:
// position indicates the point in time from which you want to play the video. 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 the playback
You can call the pause
method to pause the playback. Sample code:
[self.player pause];
Stop the playback
You can call the 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
You can call scalingMode
to scale in or scale out a video without changing the original aspect ratio, or stretch a video. 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. If the aspect ratios of the video and the view are different, image distortion may occur.
self.player.scalingMode = AVP_SCALINGMODE_SCALETOFILL;
Rotation
You can call the 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
You can call the 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 the current playback progress
You can obtain the current playback position in the onCurrentPositionUpdate callback. Sample code:
- (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
You can query the total duration of a video. You can obtain the video duration only after the video is loaded. For example, you can obtain the video duration from the onPrepared callback. Unit: milliseconds. Sample code:
-(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 obtain the current buffering progress from the onBufferedPositionUpdate callback. Sample code:
- (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
Sample code:
// Obtain the current frame rate for video rendering. The returned data is of the FLOAT data type.
[self.playergetOption:AVP_OPTION_RENDER_FPS]
// Obtain the current video bitrate. The returned data is of the FLOAT data type. Unit: bit/s.
[self.playergetOption:AVP_OPTION_VIDEO_BITRATE]
// Obtain the current audio bitrate. The returned data is of the FLOAT data type. Unit: bit/s.
[self.playergetOption:AVP_OPTION_AUDIO_BITRATE]
// Obtain the current network downlink bitrate. The returned data is of the FLOAT data type. Unit: bit/s.
[self.playergetOption:AVP_OPTION_DOWNLOAD_BITRATE]
Obtain the playback status
You can obtain the player status from the onPlayerStatusChanged callback. Sample code:
- (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 playback is complete.
}
break;
case AVPStatusError:{
// A playback error occurs.
}
break;
default:
break;
}
}
Set the volume
You can adjust the player volume or configure the mute mode for the playback.
Adjust 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. After you set a volume, you can query the volume information. Sample code:
// Set the volume to a real number from 0 to 2.
self.player.volume = 1.0f;
// Obtain the volume.
self.player.volume
Configure the mute mode
Call the muted
method to mute a video that is being played. Sample code:
self.player.muted = YES;
Set the playback speed
ApsaraVideo Player SDK for iOS allows you to 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. 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
Configure UrlSource-based live streaming
You can play live streams based on URLs in ApsaraVideo Live or URLs of the transcoded live streams. Default transcoding and custom transcoding are supported. For more information about how to transcode live streams, see Transcoding management. For more information about how to obtain streaming URLs, see Ingest and streaming URLs.
You can switch between live streams in different definitions. Only Real-Time Messaging Protocol (RTMP) and Flash Video (FLV) streams are supported.
You must set the group of pictures (GOP) size to 2 seconds and the timestamp to the time when the source video is pushed.
If you change the streaming URL to a URL that does not meet the preceding requirements, the switching fails.
Switch between definitions
Call switchStream
to switch between live streams in different definitions. Specify the URL of the live stream that you want to play.
[self.player switchStream:newUrl];
Set the callbacks for definition switching
Configure the callbacks for the successful and failed definition switching.
// The callback that is fired when the definition switching is successful.
- (void)onStreamSwitchedSuccess:(AliPlayer*)player URL:(NSString*)URL;
// The callback that is fired when the definition switching fails.
- (void)onStreamSwitchedFail:(AliPlayer*)player URL:(NSString*)URL errorModel:(AVPErrorModel *)errorModel;
Configure VidAuth- or VidSts-based playback
If you use VidAuth or VidSts to play on-demand videos, no additional settings are required. 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;
}
}
}
Switch between definitions
You can call the selectTrack
method and specify the track index that corresponds to the definition in which you want to play the video.
[self.playerselectTrack:index];
Set the callbacks for definition switching
The onTrackChanged callback is invoked after the video definition is switched.
- (void)onTrackChanged:(AliPlayer*)player info:(AVPTrackInfo*)info {
// The 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. Sample code:
self.player.loop = YES;
The AVPEventLoopingStart
callback is invoked when loop playback starts. Sample code:
- (void)onPlayerEvent:(AliPlayer*)player eventType:(AVPEventType)eventType {
switch (eventType) {
case AVPEventLoopingStart:
break;
}
}
Switch audio tracks
ApsaraVideo Player SDK for iOS supports audio track switching. This allows you to switch audio tracks in different languages during video playback.
Usage notes
You can switch audio tracks in streams that are not used for list playback such as MP4 streams, single-bitrate mixed HLS streams, audio tracks in single-bitrate HLS streams, and substreams in multi-bitrate mixed HLS streams. The following table describes different types of video streams.
Type | Video stream suffix | Bitrate quantity | M3U8 file quantity | Substream type | Description |
Non-list stream (such as MP4 stream) | .mp4 | 1 | - | A stream that contains a video track, multiple audio tracks, and multiple subtitle tracks. | You can switch between audio tracks. |
Single-bitrate mixed HLS stream | .m3u8 | 1 | 1 | A stream that contains a video track, multiple audio tracks, and multiple subtitle tracks. | You can switch between audio tracks. |
Single-bitrate HLS stream | .m3u8 | 1 | n | An M3U8 stream that contains only video tracks, audio tracks, or subtitle tracks. | You can switch between audio tracks. |
Multi-bitrate mixed HLS stream | .m3u8 | n | n | An M3U8 stream that contains a video track, multiple audio tracks, and multiple subtitle tracks. The bitrate of the substreams are different. | You can switch between different substreams. You cannot switch between the audio tracks of a substream. |
Procedure
Configure callbacks.
// Configure the onSubTrackReady callback. In most cases, the onSubTrackReady callback is fired before the prepare callback. - (void)onSubTrackReady:(AliPlayer*)player info:(NSArray<AVPTrackInfo*>*)info { // Call the getSubMediaInfo operation and obtain MediaInfo from the response. You must call the getSubMediaInfo operation after the onSubTrackReady is returned. Otherwise, an empty string is returned. AVPMediaInfo* subMediaInfo = [player getSubMediaInfo]; // Traverse all elements in the array. for (int i=0; i<subMediaInfo.tracks.count; i++) { AVPTrackInfo* track = [mediaInfo.tracks objectAtIndex:i]; // Obtain the audio track that you want to play. } }
Switch to the desired audio track.
[self.player selectTrack:myTrack.trackIndex accurate:YES]