How to Play a Video from Either a Local or a Server Url in iOS

How to play a video from either a local or a server URL in iOS

1.First of all add MediaPlayer.Framework in XCode

2.Then add #import < MediaPlayer/MediaPlayer.h > in your viewController's .h file

3.Now implement this code in your viewDidLoad Method

     //NSString *filepath = [[NSBundle mainBundle] pathForResource:@"aaa" ofType:@"mp4"];  
//NSURL *fileURL = [NSURL fileURLWithPath:filepath];

NSURL *fileURL = [NSURL URLWithString:@"http://www.ebookfrenzy.com/ios_book/movie/movie.mov"];

moviePlayerController = [[MPMoviePlayerController alloc] initWithContentURL:fileURL];
[moviePlayerController.view setFrame:CGRectMake(0, 70, 320, 270)];
[self.view addSubview:moviePlayerController.view];
moviePlayerController.fullscreen = YES;
[moviePlayerController play];

For Orientation Please add this code

 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
if (interfaceOrientation == UIInterfaceOrientationPortrait || interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown) {
[moviePlayerController.view setFrame:CGRectMake(0, 70, 320, 270)];
} else if (interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight) {
[moviePlayerController.view setFrame:CGRectMake(0, 0, 480, 320)];
}
return YES;
}

In this code moviePlayerController is MPMoviePlayerController declared in .h file

Playing a video file from server in an Iphone app

This is the common way to play video file from server or from local path.


MPMoviePlayerController *player =[[MPMoviePlayerController alloc] initWithContentURL: myURL];
[[player view] setFrame: [myView bounds]]; // frame must match parent view
[myView addSubview: [player view]];
[player play];

You can do using html5's video tag(provided you are using UIWebView).


- (void)viewDidLoad {
[super viewDidLoad];

//to play from actual server location
//[self playVideo:@"file://localhost/Users/PlayVideos/3idiots.mov" frame:CGRectMake(20, 70, 280, 250)];

//from server (http://www.example.com/video.mov)..... http://www.ebookfrenzy.com/ios_book/movie/movie.mov
[self playVideo:@"your server URL" frame:CGRectMake(20, 70, 280, 250)];
}

- (void)playVideo:(NSString *)urlString frame:(CGRect)frame {
NSString *embedHTML = @"\
<html><head>\
<style type=\"text/css\">\
body {\
background-color: transparent;\
color: white;\
}\
</style>\
<script>\
function load(){document.getElementById(\"yt\").play();}\
</script>\
</head><body onload=\"load()\"style=\"margin:0\">\
<video id=\"yt\" src=\"%@\" \
width=\"%0.0f\" height=\"%0.0f\" autoplay controls></video>\
</body></html>";
NSString *html = [NSString stringWithFormat:embedHTML, urlString, frame.size.width, frame.size.height];
UIWebView *videoView = [[UIWebView alloc] initWithFrame:frame];
[videoView loadHTMLString:html baseURL:nil];
[self.view addSubview:videoView];
[videoView release];
NSLog(@"%@",html);
}

How to play movie with a URL using a custom NSURLProtocol?

UPDATE: I spoke to Apple about this and it's not possible to use MPMoviePlayerController with a NSURLProtocol subclass at the moment!


Hej,

I am not sure but it could be possible. I am currently working on something similar but haven't got it fully working. What I have found out is that MPMoviePlayerController interacts with my custom NSURLProtocol subclass BUT it seems to be important to take the HTTPHeaders of the NSURLRequest into account because they define a range of bytes the MPMoviePlayerController needs.

If you dump them in your NSURLProtocol subclass you will get something like this twice for the start:

2011-01-16 17:00:47.287 iPhoneApp[1177:5f03] Start loading from request: {
Range = "bytes=0-1";

}

So my GUESS is that as long as you can provide the correct range and return a mp4 file that can be played by the MPMoviePlayerController it should be possible!

EDIT: Here is a interesting link: Protecting resources in iPhone and iPad apps

iPhone : How to play local video in WebView?

NSString *Str = @"<video controls> <source src=\"yourvideofile.mp4\"> </video>";
NSString *path = [[NSBundle mainBundle] pathForResource:@"yourvideofile" ofType:@"mp4"];
[Webview loadHTMLString:Str baseURL:[NSURL fileURLWithPath:path]];

Swift 4 & Xcode 10. Play video on app launch, when complete, reveal view controller

Firstly change your launch screen storyboard to Main storyboard from project settings in General tab.

Create one view controller with following name and write code to implement AVPlayer to play video.

import UIKit
import AVFoundation

class VideoLaunchVC: UIViewController {

func setupAVPlayer() {

let videoURL = Bundle.main.url(forResource: "Video", withExtension: "mov") // Get video url
let avAssets = AVAsset(url: videoURL!) // Create assets to get duration of video.
let avPlayer = AVPlayer(url: videoURL!) // Create avPlayer instance
let avPlayerLayer = AVPlayerLayer(player: avPlayer) // Create avPlayerLayer instance
avPlayerLayer.frame = self.view.bounds // Set bounds of avPlayerLayer
self.view.layer.addSublayer(avPlayerLayer) // Add avPlayerLayer to view's layer.
avPlayer.play() // Play video

// Add observer for every second to check video completed or not,
// If video play is completed then redirect to desire view controller.
avPlayer.addPeriodicTimeObserver(forInterval: CMTime(seconds: 1, preferredTimescale: 1) , queue: .main) { [weak self] time in

if time == avAssets.duration {
let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ViewController") as! ViewController
self?.navigationController?.pushViewController(vc, animated: true)
}
}
}

//------------------------------------------------------------------------------

override func viewDidLoad() {
super.viewDidLoad()
}

//------------------------------------------------------------------------------

override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.setupAVPlayer() // Call method to setup AVPlayer & AVPlayerLayer to play video
}
}

Main.Storyboard:
Video Launch VC

Project Launch Screen File:
Project Launch Screen File

See following video also:

https://youtu.be/dvi0JKEpNTc

Play video by default in full screen

Try this.

#define degreesToRadian(x) (M_PI * (x) / 180.0)

-(void)playMovieAtURL:(NSURL*)movieURL
{
if ([NSClassFromString(@"MPMoviePlayerController") instancesRespondToSelector:@selector(view)])
{

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 30200

// running iOS 3.2 or better
mViewPlayer = [[MPMoviePlayerViewController alloc] initWithContentURL:movieURL];
mViewPlayer.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;

CGRect newFrame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
mViewPlayer.view.frame = newFrame;

CGAffineTransform landscapeTransform;
landscapeTransform = CGAffineTransformMakeRotation(degreesToRadian(90));
landscapeTransform = CGAffineTransformTranslate(landscapeTransform, 80, 80);

[mViewPlayer.view setTransform: landscapeTransform];

[self.view addSubview:mViewPlayer.view];

[mViewPlayer.moviePlayer play];

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(movieDidExitFullscreen:)
name:MPMoviePlayerPlaybackDidFinishNotification
object:[mViewPlayer moviePlayer]];
#endif
}
else
{
MPMoviePlayerController *mMPPlayer = [[MPMoviePlayerController alloc] initWithContentURL:movieURL];

mMPPlayer.scalingMode=MPMovieScalingModeFill;
mMPPlayer.backgroundColor=[UIColor blackColor];

[mMPPlayer play];

[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(moviePlayerDidFinish:)
name:MPMoviePlayerPlaybackDidFinishNotification
object:mMPPlayer];
}
}

/*---------------------------------------------------------------------------
*
*--------------------------------------------------------------------------*/

- (void) movieDidExitFullscreen:(NSNotification*)notification
{
//[[UIApplication sharedApplication] setStatusBarHidden:YES];

/*/ Remove observer
[[NSNotificationCenter defaultCenter]
removeObserver:self
name:MPMoviePlayerPlaybackDidFinishNotification
object:nil];

[self dismissModalViewControllerAnimated:YES];*/

[[NSNotificationCenter defaultCenter] removeObserver: self
name:MPMoviePlayerPlaybackDidFinishNotification
object: [notification object]];

MPMoviePlayerController *theMovie1 = [notification object];

[theMovie1.view removeFromSuperview];
[theMovie1 release];
}

- (void) moviePlayBackDidFinish:(NSNotification*)notification
{
//[[UIApplication sharedApplication] setStatusBarHidden:YES];

/*/ Remove observer
[[NSNotificationCenter defaultCenter]
removeObserver:self
name:MPMoviePlayerPlaybackDidFinishNotification
object:nil];

[self dismissModalViewControllerAnimated:YES];*/

[[NSNotificationCenter defaultCenter] removeObserver: self
name:MPMoviePlayerPlaybackDidFinishNotification
object: [notification object]];

MPMoviePlayerController *theMovie1 = [notification object];

[theMovie1.view removeFromSuperview];
[theMovie1 release];
}

How can I stream a movie in iOS and playback from the filesystem later?

You can do this as of iOS 10 with AVAssetDownloadTask. See this WWDC 2016 session and this documentation.

Alternatively, if your movie isn't DRM'd, you can do it with AVAssetResourceLoaderDelegate, which effectively lets you give an AVPlayer an arbitrary stream of bytes. See this walkthrough.



Related Topics



Leave a reply



Submit