iOS-Player-SDK-Developer Guide
Cocoapods Access
It is very simple to use Cocoapods access method, please see Cocoapods Access Method.
If you use Cocoapods access method, you can skip the following preparations before developing
and XCode project settings
.
Preparations Before Developing
- Download the latest Player iOS SDK.
- Prepare for iOS running environment: All the systems in IOS 7.0 and above versions.
- Xcode version: It is recommended to use Xcode 8.1.
- Adaptive to CPU instruction set: armv7/armv7s、arm64、i386/x86_64.
- Apply for an account and enable the privileges: You have to log into Baidu AI Cloud and get AK/SK on the Security Authentication Page.
- Add iOS framework, audio encoding and decoding API (AudioToolbox.framework) and compression tools (libbz2.tbd and libz.tbd).
XCode Project Configuration
Configure App Transport Security (ATS)
From iOS 9.0 and OS X v10.11, App Transport Security (ATS) feature is enabled by default. ATS uses HTTPS to access to Web service mandatorily, and it must use version above TLS v1.2 to ensure communication security. See the following for detailed need of ATS : Requirements for Connecting Using ATS
If App supports iOS 9.0, and needs to access to Web service not meeting the requirements above, NSAppTransportSecurity
element must be used in info.plist file to add exceptional processing rule. See the following for use method of NSAppTransportSecurity
: App Transport Security
As the service accessed by AK authorization cannot meet the requirements of ATS, the following configurations need to be set in info.plist file to modify the access behavior of ATS to the domain name drm.media.baidubce.com
.
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>drm.media.baidubce.com</key>
<dict>
<key>NSIncludesSubdomains</key>
<true/>
<key>NSExceptionAllowInsecureHTTPSLoads</key>
<true/>
<key>NSExceptionRequiresForwardSecrecy</key>
<false/>
<key>NSExceptionMinimumTLSVersion</key>
<string>TLSv1.0</string>
</dict>
</dict>
</dict>
Set Building Setting
- Set the CPU instruction set
iOS SDK supports four CPU frameworks, including armv7, arm64, x86 and x86_64. Please check the "Build Settings -> Architectures -> Valid Architectures " and “Build Settings -> Architectures -> Architectures " settings to ensure that no other CPU instruction sets are included.
- Disable Bitcode compilation option
If you use XCode 7, please close Bitcode compiler option “Build Settings->Build Option->Enable Bitcode”. Because the iOS SDK library doesn’t contain Bitcode command.
- Enable Module compilation option
As shown in the figure below, opening the option Module "Build Settings->Apple LLVM - Language - Modules->Enable Modules(C and Objective-C)" is conducive to simplifying the configuration of dependent libraries
- Set
Other Linker Flags
inBuild Settings
, and add a parameter-ObjC
Add iOS SDK header file
Add the header file CyberPlayerController.h under the directory of Baidu-T5Player-SDK-iOS-x.x.x/include to Xcode project.
Add the static link library of iOS SDK
Please add the static link library of iOS SDK in “Build Phases->Link Binary with Libraries”
Add iOS system dynamic link library
Please add the listed system library in the following chart in “Build Phases->Link Binary with Libraries” Figure 6 SDK Dependent Framework
Frame name | Description |
---|---|
libbz2.tbd | Compression tool |
libz.tbd | Compression tool |
AudioToolbox.framework | Audio processing tool |
Complete the setup of the static link library of iOS SDK and dynamic link library of system, as shown in the figure below:
Play Developer Guide
The following introduces how to call the packed API in the player SDK to finish all the operations.
Create and set CyberPlayerController instance
CyberPlayerController is the core API of iOS SDK, and the developer must first create this type of instance to play videos and audios. You have to set the video playback address and Baidu AI Cloud Access Key separately.
- Set Access key of Baidu AI Cloud The user of Baidu AI Cloud will be assigned with a pair of Access Key and Private Key after the identity authentication. Introduce Access Key before playing the video for SDK to make authentication certificate. If no Access Key is passed in or if an invalid Access Key is passed in, a warning message is displayed during the playback.
- Set video play address Video play address can be set through property contentURL or contentString. When the player is playing a video, a new video is not be played by setting contenString/contenURL. If you want to play a new video, you need to call prepareToplay method.
The following code displays how to create and set CyberPlayerController by using video play address URL and Access Key.
CyberPlayerController *cbPlayerController = [[CyberPlayerController alloc] init];
NSURL *url = [NSURL URLWithString:@”<video url>”];
cbPlayerController.contentURL = url;
NSString* msAK=@"<AccessKey>";
[cbPlayerController setAccessKey:msAK];
Note
- The current version only supports a single instance CyberPlayerController object, and multiple instances will cause playback exception.
- The current version does not support Baidu video resources (bdhd://video resources at the beginning).
Play the video
After the player setting the video play address, prepareToPlay method should be called to initialize the video files. After initializing, CyberPlayerLoadDidPreparedNotification notification is sent and the isPreparedToPlay attribute is set to be YES. After initializing, if shouldAutoplay attribute is YES, automatically call play method to play; if shouldAutoplay attribute is NO, prepare to call play or start method to play.
At the beginning, the player will pause for a period of time to cache a certain amount of video, which can offset the network stutter caused by network jitter and ensure the smooth playback of the video. The property corresponding to the time span is cachePauseTimeInSeconds (the default value is 1.0). The larger the value, the smaller the impact of network jitter on video playback, but the delay will increase; otherwise, the smaller the value, the larger the impact of network jitters on video playback, and the smaller the delay of playback will be. In the live scenario, you should set an appropriate value for cachePauseTimeInSeconds according to the network conditions and video code rate to balance the play lags and live delay. In case of high bandwidth, it is suggested to reduce the cache to reduce the delay; in case of low bandwidth, it is recommended to improve the cache to improve the smoothness of playback.
Automatic playback
cbPlayerController.shouldAutoplay = YES;
[cbPlayerController prepareToPlay];
At this point, the attribute of shouldAutoplay is YES, the player will call play to play the video automatically after the completion of prepareToPlay method.
Monitor CyberPlayerLoadDidPreparedNotification notifications
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(preparedDone:)
name:CyberPlayerLoadDidPreparedNotification
object:nil];
cbPlayerController.shouldAutoplay = NO
[cbPlayerController prepareToPlay];
Meanwhile, create preparedDone method, and call start or play method in that method.
(void) preparedDone: (NSNotification*)aNotification {
[cbPlayerController start];
}
Note
If prepareToPlay is not called to complete the initialization of the video file by the player before the play method is called, the player will call prepareToPlay automatically to initialize the video file.
Pause play
Call pause method to stop video play, call play or start method to restart play.
[cbPlayerController pause];
Change the playing position
SDK provides multiple methods to change play positions.
When initializing
When the attribute of isPreparedToPlay is NO, in order to change the initial moment of video playback, three ways can achieve the same effect:
- Set the property of initialPlaybackTime
- Set currentPlaybackTime sttribute
- Call seekto method.
When playing
When calling seekTo or setting currentPlaybackTime during the process of playing, the play starts from the assigned position. If the current video is a network video, it may trigger buffer CyberPlayerStartCachingNotification notification. If you want to response the cache process in UI, please monitor CyberPlayerGotCachePercentNotification notifications.
HLS multiple code rate/resolution ratio switchover
For HLS multi-code rate videos, when the player finishes video format parsing and is ready to play, you can display the code rate list through getSupportedBitrates
or display the resolution list through getSupportedResolution
. Code rate and resolution ratio are one-to-one corresponded, generally divided into two levels (low and high, and the default level is low) or three levels (low medium and high, and the default level is medium); it is suggested to select the display code rate of resolution ratio according to the habits of the end-user. When manual switch is enabled, you can get the current code selectBitrate through getBitrateIndex
and select a new code rate through selectBitrate
.
Stop play
[cbPlayerController stop];
When the play is stopped, send CyberPlayerPlaybackDidFinishNotification notification.
Note
The stop method is asynchronous operation; when it returns, you should not call prepareToPlay to play other videos immediately, and must wait for receiving CyberPlayerPlaybackDidFinishNotification to play.
M3U8 video download
The player supports download and management for M3U8 videos.
Header file
Header file | Description | Key information |
---|---|---|
CyberDownloader.h | Information related to download management | downloadTaskWithURL 、suspendTask 、resumeTask 、cancelTask 、stopAllTasks 、resumeUncompletedTasks Interface |
CyberDownloadTask.h | Information related to download tasks | |
CyberMediaItem.h | Information related to the local storage of the videos | task.item.index sttribute |
Download management interface
Interface | Description | Description |
---|---|---|
downloadTaskWithURL |
Create the download task | Assign the URL and title of a target video, create a task and add it in the task pipeline; whether to execute the task is determined by the number of tasks being executed, and four tasks are supported to be downloaded simultaneously by default |
suspendTask |
Pause the download task | Use cooperatively with resumeTask After pausing the task, the downloaded videos are still locally stored and the tasks are removed from the download pipeline |
resumeTask |
Resume the download tasks | Use cooperatively with suspendTask . After the task is resumed, it enters the download task queue again, and continues the task at the breakpoint based on the downloaded part |
cancelTask |
Cancel download tasks | Comparing with suspendTask , the cancelled tasks are removed from the task pipeline, and the corresponding videos are also deleted from local as well. |
stopAllTasks |
Stop the download tasks in batch | The disposal for local videos is similar with suspendTask , meaning to locally store the downloaded videos suspendTask aims at single task, while stopAllTasks is batch operation |
resumeUncompletedTasks |
Resume download tasks in batches | resumeTask aims at single task, while resumeUncompletedTasks is batch operation |
frozen |
Freeze the download queue | You can call this method when you want to cancel some tasks but do not want tasks in the waiting state to be scheduled. |
clean |
Delete all downloaded data | All videos previously downloaded will be removed. After the call, the object cannot be used. |
Download and play
1.Call initWithUser:delegate:
to finish initialization.
`user` disposes the user-related events and `delegate` disposes task-related events.
Function prototype:
- (instancetype)initWithUser:(NSString*)user delegate:(id<CyberDownloaderDelegate>)delegate;
2.Call downloadTaskWithURL:title:error:
to create the download task.
Function prototype:
- (CyberDownloadTask*)downloadTaskWithURL:(NSString*)url title:(NSString*)title error:(NSError**)error;
`downloadTaskWithURL:title:error:` first checks `error` returned value; if the value is `CyberDownloadErrorCodeOK`, it means the video can be downloaded, and then create the task and add it to the download task pipeline (the download does not actually begin, further call `taskStart` to activate download when there is available resource in the pipeline); or please refer to the following error code list to adjust:
|Error code |Description |
| ---------------------------------------- | -------------- |
| CyberDownloadErrorCodeAlreadyExists |The video file has existed and has been downloaded |
| CyberDownloadErrorCodeProtocolNotSupport |Protocol does not support |
3.When the download task starts, call back taskStart:
.
Function prototype:
- (void)taskStart:(CyberDownloadTask*)task;
Now, the interfaces of suspend (`suspendTask:`), resume (`resumeTask:`), cancel (`cancelTask:`) and batch stop (`stopAllTasks:`) to manage the download tasks.
4.Call back task:progress:
during the process of task downloading to inform the task process.
Function prototype:
- (void)task:(CyberDownloadTask*)task progress:(float)progress;
5.After finishing task download, call back taskEnd:error:
. If error is empty, executed the download task successfully; otherwise, task failed.
Function prototype:
- (void)taskEnd:(CyberDownloadTask*)task error:(NSError*)error;
6.After downloading successfully, transfer the task.item.index attribute to the player for local play.
In addition, you can also call `mediaItems ` to query videos which have been downloaded or are being downloaded to local disk or call ``removeMediaItem:` to delete a specified video.