How to Develop an avplayer iPad Program

Source: Internet
Author: User

Original article: http://klanguedoc.hubpages.com/hub/iOS-How-To-Implement-AirPlay-in-an-AVPlayer-iPAD-Application

Airplay is not a new thing. It exists in the IOS 4.3 SDK. However, new things are constantly added to the airplay API. An interesting new feature is that the iPad program can play content from IOS devices or mirror the Screen Content on iPad 2 through Apple TV 2.

In short, airplay places media content on HD monitors (TVS) or HD sound systems. Apple TV 2 is a bridge between iOS devices or between iTunes and HD devices.

With the advent of iOS 5, any program using the AV foundation class can deliver audio and video content from the program to Apple TV. You can use mpmoviewplayercontroller to project the currently playing content to a HDTV or other HD display devices through airplay. Another improvement is video placement from uiwebview, which is an exciting improvement because it means that we can directly project online audio and video to TV or Apple TV 2 from the web.

Use avfoundation to project video content

To use avfoundation in an application, you need to implement avplayer and set allowsairplayvideo to yes to enable airplay, or set it to no to disable airplay, as shown in the following code:

-(BOOL)setAirPlay:(BOOL)airplayMode{

   return self.player.allowsAirPlayVideo=airplayMode;

}

Write Applications

To demonstrate how to create an avplayer application and implement airplay, we will create a single view application (check usestoryboards), create an avplayer class, and implement the airplay feature.

  • Create a single view application. You can select iPhone, iPod, or iPad as the target type. After creating a project, import it to the AV foundation framework.
  • Create a new class named player and inherit the uiview class. Add the avplayer class to the header file and add an avplayer attribute. See the following code.

@class AVPlayer;

@interface Player : UIView

@property(nonatomic, strong) AVPlayer * player;

  • The next step is to implement the player class.
  • We have implemented at least four methods to be implemented for the most basic avplayer, and also provided a method as our airplay switch.
  • First, we need a package class for the avlayer class. This class is a calayer subclass used to manage the visible content of a media set. The code for creating a packaging class is as follows:

+ (Class)layerClass {

    return [AVPlayerLayer class];

}

  • Then, we need a method to instantiate an avplayer object (which we defined in the header file ). See the following code.

-(AVPlayer *) player{

    return [(AVPlayerLayer *)[self layer] player];

}

  • In the setplayer method, as shown in the following code, an avplayer parameter is used to add an avplayer instance to uiview. This uiview subclass will be used in the main view controller.

- (void)setPlayer:(AVPlayer*)player {

    [(AVPlayerLayer*)[self layer] setPlayer:player];

}

  • The last method of this class is the setairplay method. The parameter is used to specify the allowsairplayvideo attribute of avplayer uiview (player. See the following code.

-(BOOL)setAirPlay:(BOOL)airplayMode{

   return self.player.allowsAirPlayVideo=airplayMode;

}

When you specify a layer (avplayerlayer) for the video output, you can specify any number of layers, as long as you can easily control the content display. For example, processing the time synchronization between audio and video. With setdisplaymode, you can set a layer for display. First, create an avplayerlayer object as the display layer, and then modify its attributes. The default value is the avlayervideogravityresizeaspect attribute. You can also set the avlayervideogravityresizeaspectfill attribute and avlayervideogravityresize attribute. Avlayervideogravityresizeaspect keeps the video aspect ratio and automatically adjusts the playback content to the size of the playback window. Avlayervideogravityresizeaspectfill is similar to the former, but it fills in the playing content rather than adapting to the size of the playing window. The last value will stretch the playing content to adapt to the playing window.

The complete code of the player class is as follows:

#import <UIKit/UIKit.h>

#import <AVFoundation/AVFoundation.h>

@class AVPlayer;

@interface Player : UIView

@property(nonatomic, strong) AVPlayer * player;

-(BOOL) setAirPlay:(BOOL) airplayMode;

@end

#import "Player.h"

#import <AVFoundation/AVFoundation.h>

@implementation Player

+ (Class)layerClass {

    return [AVPlayerLayer class];

}

-(AVPlayer *) player{

    return [(AVPlayerLayer *)[self layer] player];

}

- (void)setPlayer:(AVPlayer*)player {

    [(AVPlayerLayer*)[self layer] setPlayer:player];

}

//Enable or disable AirPlay mode

-(BOOL)setAirPlay:(BOOL)airplayMode{

   return self.player.allowsAirPlayVideo=airplayMode;

}

@end

Use player (uiview subclass) in a program)

The above Code includes the. h file and. M file of player (uiview subclass of avplayer.

To use this avplayer view in a uiviewcontroller, open the storyboard of xcode, provided that the "usestoryboard" option is used during project creation ). Select uiview (not uiviewcontroller) and change its class to player. You can enter the customeclass field in the identity panel, or select from its drop-down list.

  • Open the assistant editor and create an iboutlet for the player of the uiview subclass. Right-click the view and drag it to the header file on the right. As shown in.

Create an ibactions and iboutlets connection

  • Create a delegate to klviewcontroller. Right-click the player and drag a connection line from iboutlet to klviewcontroller (yellow block on the dock), as shown in.

Add a delegated connection klviewcontroller

Add a toolbar to the story version. Add two buttons in the toolbar to set the label text to play and pause respectively. Add a switch to switch the airplay status. Create the corresponding ibaction for the three controls (you can use the assistant editor ). The rest is done in the klviewcontroller class.

  • Open the klviewcontroller. h file, add the @ class player and @ Class avplayer statements, and import the avfoundation framework and player. h. For the source code, see:
 

#import <UIKit/UIKit.h>

#import <AVFoundation/AVFoundation.h>

#import "Player.h"

@class Player;

@class AVPlayer;

@interface klViewController : UIViewController

  • Declare An avplayer attribute for loading to the palyer view.
  • Declare An nsurl attribute. Then the iboutlet of the switch control (created using assistant editor ).
  • The kvliewcontroller. h file code is as follows:

#import <UIKit/UIKit.h>

#import <AVFoundation/AVFoundation.h>

#import Player.h

@class Player;

@class AVPlayer;

@interface klViewController : UIViewController

@property(nonatomic, strong) AVPlayer * myPlayer;

@property(nonatomic, strong) NSURL * avContentUrl;

@property (strong, nonatomic) IBOutlet Player *airPlayView;

@property (nonatomic, retain) IBOutlet UISwitch * AirPlaySwitch;

- (IBAction)PlayVideo:(id)sender;

- (IBAction)PauseVideo:(id)sender;

- (IBAction)isAirPlayOn:(id)sender;

@end

  • Next is the class implementation file. In the viewdidload method, use the URL of a video file to initialize avcontenturl:

avContentUrl = [[NSURL alloc] initWithString:@"Http://somedomain.yourvideo. MP4"];

  • Then, use avcontenturl to initialize an avplayer, which is used to assign values to the myplayer attribute defined in the header file. Assign myplayer to the player attribute of airplayview. airplayerview is a player object. See the following code:

self.myPlayer = [AVPlayer playerWithURL:avContentUrl];

[airPlayView setPlayer:[self myPlayer]];

  • Now, you need to implement the video play and pause functions of the two buttons and the airplay function of the switch control. The code for the Action Method of the playback button is as follows:

- (IBAction)PlayVideo:(id)sender {

    [self.myPlayer play];

}

  • The code of the pause button action method is as follows:

- (IBAction)PauseVideo:(id)sender {

    [self.myPlayer pause];

}

  • The action method code of the switch control is as follows:

- (IBAction)isAirPlayOn:(id)sender {

    AirPlaySwitch = (UISwitch *) sender;

    if (AirPlaySwitch.on) {

        [airPlayView setAirPlay:NO];

    }else

    {

        [airPlayView setAirPlay:YES];

    }

}

End

Another airplay-related attribute isUsesairplayvideowhileairplayscreenisactiveIt is used to automatically switch the avplayer to airplay during playback, of course, only when airplay is enabled. The default value is false.

To run this sample program, you must connect the iPad to the same Wi-Fi network of Apple TV on the iPad. Then, the URL of the video resource must be valid. Airplay is invalid in the simulator.

Klviewcontroller. h file

#import <UIKit/UIKit.h>

#import <AVFoundation/AVFoundation.h>

#import "Player.h"

@class Player;

@class AVPlayer;

@interface klViewController : UIViewController

@property(nonatomic, strong) AVPlayer * myPlayer;

@property(nonatomic, strong) NSURL * avContentUrl;

@property (strong, nonatomic) IBOutlet Player *airPlayView;

@property (nonatomic, retain) IBOutlet UISwitch * AirPlaySwitch;

 - (IBAction)PlayVideo:(id)sender;

 - (IBAction)PauseVideo:(id)sender;

 - (IBAction)isAirPlayOn:(id)sender;

 @end

Klviewcontroller. M file

#import "klViewController.h"

 @implementation klViewController

@synthesize airPlayView;

@synthesize avContentUrl, myPlayer, AirPlaySwitch;

- (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.

}

 #pragma mark - View lifecycle

 - (void)viewDidLoad

{

    [super viewDidLoad];

     //This is an Apple sample video

    avContentUrl = [[NSURL alloc] initWithString:@"Http://somedomain.yourvideo. MP4"];

    self.myPlayer = [AVPlayer playerWithURL:avContentUrl];

    [airPlayView setPlayer:[self myPlayer]];

     [self.myPlayer play];

}

 - (void)viewDidUnload

{

     [self setAirPlayView:nil];

    [super viewDidUnload];

    // Release any retained subviews of the main view.

    // e.g. self.myOutlet = nil;

}

 - (void)viewWillAppear:(BOOL)animated

{

    [super viewWillAppear:animated];

}

 - (void)viewDidAppear:(BOOL)animated

{

    [super viewDidAppear:animated];

}

 

- (void)viewWillDisappear:(BOOL)animated

{

    [super viewWillDisappear:animated];

}

 - (void)viewDidDisappear:(BOOL)animated

{

    [super viewDidDisappear:animated];

}

 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation

{

    // Return YES for supported orientations

    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);

}

 - (IBAction)PlayVideo:(id)sender {

    [self.myPlayer play];

 

}

 

- (IBAction)PauseVideo:(id)sender {

    [self.myPlayer pause];

 }

 - (IBAction)isAirPlayOn:(id)sender {

    AirPlaySwitch = (UISwitch *) sender;

    if (AirPlaySwitch.on) {

        [airPlayView setAirPlay:NO];

    }else

    {

         [airPlayView setAirPlay:YES];

    }

}

 @end

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.