Not able to play video file on iPad using AVPlayerViewController - ios

I have seen exactly the same issue here but its unanswered so asking the same question again.
AVPlayer wont play video from url in iOS9
I tried all various ways to try to play the video but unfortunately they are not working for me.
Here is the code :
AVPlayerViewController *playerViewController = [[AVPlayerViewController alloc] init];
NSString *url = [[NSBundle mainBundle] pathForResource:#"Intro" ofType:#"mp4"];
_asset = [AVURLAsset assetWithURL: [NSURL URLWithString:url]];
_playerItem = [AVPlayerItem playerItemWithAsset: _asset];
_player = [[AVPlayer alloc] initWithPlayerItem: _playerItem];
[playerViewController.view setFrame:_videoView.frame];
playerViewController.showsPlaybackControls = YES;
[_videoView addSubview:playerViewController.view];
playerViewController.player = _player;
[_player play];
and here is the screen shot of what it looks like currently by using above code. And I used another Apple code to check the video and it worked fine but the Apple code is like too much for me as its too complicated for simple things. Here it is :https://developer.apple.com/library/prerelease/ios/samplecode/AVFoundationSimplePlayer-iOS/
Thanks
AJ

I was finally able to figure this out by again looking into Apple's Sample code.
Solution:
Added the AAPLPlayerView files to my project.
Then changed my UIView in Storyboard to above class
Then updated below lines of code into my view controller class:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
self.playerView.playerLayer.player = self.player;
NSURL *movieURL = [[NSBundle mainBundle] URLForResource:#"Intro" withExtension:#"mp4"];
self.asset = [AVURLAsset assetWithURL:movieURL];
self.playerItem = [AVPlayerItem playerItemWithAsset: self.asset];
[self.player play];
}
- (AVPlayer *)player {
if (!_player)
_player = [[AVPlayer alloc] init];
return _player;
}
- (AVPlayerLayer *)playerLayer {
return self.playerView.playerLayer;
}
- (AVPlayerItem *)playerItem {
return _playerItem;
}
- (void)setPlayerItem:(AVPlayerItem *)newPlayerItem {
if (_playerItem != newPlayerItem) {
_playerItem = newPlayerItem;
// If needed, configure player item here before associating it with a player
// (example: adding outputs, setting text style rules, selecting media options)
[self.player replaceCurrentItemWithPlayerItem:_playerItem];
}
}
And it worked.
The issue was the PlayerLayer was not set properly and the video was not visible due to that.

Related

AVPlayer - how to reset play button

Im working on a app which stream a audio file online. The code below is working, but when the audio file ends, the play button don't reset. The button is still pressed, and before the user can play the audio file again, the user have to press the button 2 times.
My question is: How do i reset the play button automatically after the audio file ends?
Here is my code:
-(IBAction)togglePlayPauseTapped:(id)sender
{
if(self.togglePlayPause.selected) {
[self.audioPlayer pause];
[self.togglePlayPause setSelected:NO];
} else {
[self.audioPlayer play];
[self.togglePlayPause setSelected:YES];
self.audioPlayer = [[AVPlayer alloc] init];
NSString *urlString = #"MYURL";
NSURL* urlStream = [NSURL URLWithString:urlString];
AVPlayerItem * currentItem = [AVPlayerItem playerItemWithURL:urlStream];
[self.audioPlayer replaceCurrentItemWithPlayerItem:currentItem];
[self.audioPlayer play];
}
}`
Set the delegate of audioPlayer to self and make sure the designated ViewController can receive AVAudioPlayer Delegate calls. Then implement the audioPlayerDidFinishPlaying method and call your togglePlayPauseTapped method:
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
[self togglePlayPauseTapped:nil];
}
The total should look something like this:
Edit:
And change this
self.audioPlayer = [[AVPlayer alloc] init];
To this:
self.audioPlayer = [[AVAudioPlayer alloc] init];

Multiple audio files playing at once in iOS App

I have an iOS app which works like this:
First view
3 buttons that link to different views, each has its own audio file within
Imagine user opens one view, and starts to play the audio file. When they navigate around the app, the audio file still plays which is fine, Im happy with that.
However, if user then opens the second audio file and presses play, it plays on top of the first one so 2 audios are playing together.
How do I tell the code that if another play button is pressed it should stop the first audio file that is playing??
I am using AVFoundation framework to do this
Code is as follows:
NSString *stringPath = [[NSBundle mainBundle]pathForResource:#"01" ofType:#"MP3"];
NSURL *url = [NSURL fileURLWithPath:stringPath];
NSError *error;
avPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:&error];
[avPlayer setNumberOfLoops:2];
[avPlayer setVolume:self.sliderVolumeOutlet.value];
[NSTimer scheduledTimerWithTimeInterval:.1 target:self selector:#selector(updateMyProgress) userInfo:nil repeats:YES];
-(void)updateMyProgress
{
float progress = [avPlayer currentTime]/[avPlayer duration];
self.myProgressView.progress = progress;
}
- (IBAction)sliderVolumeAction:(id)sender {
UISlider *mySlider = sender;
[avPlayer setVolume:mySlider.value];
}
- (IBAction)stopButton:(id)sender {
[avPlayer stop];
[avPlayer setCurrentTime:0];
}
- (IBAction)pauseButton:(id)sender {
[avPlayer pause];
}
- (IBAction)playButton:(id)sender {
[avPlayer play];
}
- (IBAction)backButtonEvent:(id)sender {
[self dismissViewControllerAnimated:YES completion:NULL];
}
You can check whether it is playing the previous track or not by if ([AVPlayer rate] != 0.0)
If it is playing then you can either add the next track into queue or just use this function to replace current track with the new one - (void)replaceCurrentItemWithPlayerItem:(AVPlayerItem *)item
Perhaps creating some sort of playSound function would be better suited for this. Something like this:
- (void)playSoundWithFileName:(NSString *)fileName andExtension:(NSString *)extension {
NSString *stringPath = [[NSBundle mainBundle]pathForResource:fileName ofType:extension];
NSURL *url = [NSURL fileURLWithPath:stringPath];
NSError *error;
if (avPlayer) {
[avPlayer stop];
avPlayer = nil;
}
avPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:&error];
if (error)
NSLog(#"Error");
else {
[avPlayer setNumberOfLoops:2];
[avPlayer setVolume:self.sliderVolumeOutlet.value];
[avPlayer play];
}
}
Use:
[self playSoundWithFileName:#"01" andExtension:#"MP3"];
[NSTimer scheduledTimerWithTimeInterval:.1 target:self selector:#selector(updateMyProgress) userInfo:nil repeats:YES];
and call -(void)playSoundWithFileName whenever you want to play another sound.
Or if you were using the AVPlayer class:
- (void)playSoundWithFileName:(NSString *)fileName andExtension:(NSString *)extension {
NSString *stringPath = [[NSBundle mainBundle]pathForResource:fileName ofType:extension];
NSURL *url = [NSURL fileURLWithPath:stringPath];
AVPlayerItem *item = [AVPlayerItem playerItemWithURL:url];
if (avPlayer)
[avPlayer replaceCurrentItemWithPlayerItem:item];
else
avPlayer = [AVPlayer playerWithPlayerItem:item];
[avPlayer setVolume:self.sliderVolumeOutlet.value];
[avPlayer play];
}
Though the latter doesn't allow you set a number of loops.

ipad movie paused rather play when page is loaded

I have a movie that loads fine and plays fine but it plays as soon as the page loads. I would like it to load in a paused state requiring the user to hen press play to watch.
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *moviePath = [[NSBundle mainBundle] pathForResource:#"iobserve1" ofType:#"mov"];
NSURL *movieURL = [NSURL fileURLWithPath:moviePath];
moviePlayerController = [[MPMoviePlayerController alloc] initWithContentURL:movieURL];
moviePlayerController.view.frame = CGRectMake(60, 44, 900, 656); // player's frame must match parent's
[self.movieView addSubview:moviePlayerController.view];
moviePlayerController.controlStyle = MPMovieControlStyleEmbedded;
[moviePlayerController prepareToPlay];
[moviePlayerController pause];
}
The pause on the last line does not seem to do anything. Any help? Thanks
Put your code blurb you've written above in viewwillappear.
Then add play at the end like so:
-(void) viewWillAppear: (BOOL) animated {
NSString *moviePath = [[NSBundle mainBundle] pathForResource:#"iobserve1" ofType:#"mov"];
NSURL *movieURL = [NSURL fileURLWithPath:moviePath];
moviePlayerController = [[MPMoviePlayerController alloc] initWithContentURL:movieURL];
moviePlayerController.view.frame = CGRectMake(60, 44, 900, 656); // player's frame must match parent's
[self.movieView addSubview:moviePlayerController.view];
moviePlayerController.controlStyle = MPMovieControlStyleEmbedded;
[moviePlayerController prepareToPlay];
[moviePlayerController play];
}
at the end of it.
In a viewdidappear do a
-(void) viewDidAppear: (BOOL) animated {
[moviePlayerController pause];
}
Remember to remove code from viewDidLoad
You might want to try setting the MPMoviePlayerController property shouldAutoplay to NO.
Add the following line before your prepareToPlay call;
moviewPlayerController.shouldAutoplay = NO;
From the reference:
shouldAutoplay
A Boolean that indicates whether a movie should begin playback automatically.
#property (nonatomic) BOOL shouldAutoplay
Discussion
The default value of this property is YES. This property determines
whether the playback of network-based content begins automatically
when there is enough buffered data to ensure uninterrupted playback.
Availability
Available in iOS 3.2 and later.
Declared In

iOS How to play multiple videos on one view

I was wondering how to play multiple videos in one page, like where you have two buttons, and when you press one, it plays a video, and when you press the other it plays a different one. I have this code so far:
-(void)WelcomeVideo1
{
NSURL *url31 = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"DirectorsWelcome" ofType:#"mp4"]];
welcomePlayer1 = [[MPMoviePlayerController alloc]
initWithContentURL:url31];
welcomePlayer1.controlStyle = MPMovieControlStyleDefault;
welcomePlayer1.shouldAutoplay = YES;
[self.view addSubview:welcomePlayer1.view];
[welcomePlayer1 setFullscreen:YES animated:YES];
}
-(void) moviePlayBackDidFinish:(NSNotification *)aNotification{
[welcomePlayer1.view removeFromSuperview];
welcomePlayer1 = nil;
}
- (void)moviePlayerWillExitFullscreen:(NSNotification*) aNotification {
[welcomePlayer1 stop];
[welcomePlayer1.view removeFromSuperview];
welcomePlayer1 = nil;
}
-(void)storyVideo1
{
NSURL *url4 = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"OurStory" ofType:#"mp4"]];
storyPlayer1 = [[MPMoviePlayerController alloc]
initWithContentURL:url4];
storyPlayer1.controlStyle = MPMovieControlStyleDefault;
storyPlayer1.shouldAutoplay = YES;
[self.view addSubview:storyPlayer1.view];
[storyPlayer1 setFullscreen:YES animated:YES];
}
-(void) moviePlayBackDidFinish2:(NSNotification *)aNotification{
[storyPlayer1.view removeFromSuperview];
storyPlayer1 = nil;
}
- (void)moviePlayerWillExitFullscreen2:(NSNotification*) aNotification {
[storyPlayer1 stop];
[storyPlayer1.view removeFromSuperview];
storyPlayer1 = nil;
}
but whenever I try to play both videos, the 2nd one I play crashes the app. Any ideas?
Use AVPlayer and AVPlayerLayer instead of MPMoviePlayerController.
Take a look into following apple example.

ShouldAutoplay on MoviePlayerController

I am a new developer, therefore I'm still learning and know I'm doing some things wrong. I have a segmented control object in which when the user presses one of the segments, it goes to play a video. I have it setup to where they press the segment, then have to press a play button to get the video to play. I want to cut out the play button and have it play automatically. This is where I'm having trouble. I found the shouldAutoplay option but when I use it and cut out the button, it won't take me to the video at all. I'm sure I'm not using the shouldAutoplay option correctly. Was hoping for some help or at least a point in the right direction.
- (IBAction)playMovie:(id)sender;
{
NSBundle *bundle = [NSBundle mainBundle];
NSString *moviePath = [bundle pathForResource:#"mytestimony" ofType:#"m4v"];
NSURL *movieURL = [[NSURL fileURLWithPath:moviePath] retain];
MPMoviePlayerController *theMovie = [[MPMoviePlayerController alloc] initWithContentURL:movieURL];
theMovie.shouldAutoplay = YES;
theMovie.scalingMode = MPMovieScalingModeAspectFill;
[theMovie autorelease];
MPMoviePlayerViewController *moviePlayer = [[MPMoviePlayerViewController alloc] initWithContentURL:movieURL];
[self presentMoviePlayerViewControllerAnimated:moviePlayer];
}
Have you tried [theMovie play];?
UPDATE: I just noticed you set shouldAutoplay in theMovie, but what you presented is another instance of MPMoviePlayerViewController, which is moviePlayer. That's why your movie did not autoplay. You should instead have:
[self presentMoviePlayerViewControllerAnimated:theMovie];
Don't play the video, just prepare it for playing and put the shouldAutoPlay as NO, because you don't want to video player to play it automatically.
-(void) SetVideoFile:(NSString *)fileName {
videoFileName=fileName;
moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL URLWithString:fileName]];
moviePlayer.initialPlaybackTime = 0;
moviePlayer.view.frame = self.view.frame ;
[orientationHandler VideoStart];
[self.view addSubview:moviePlayer.view] ;
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(moviePlaybackDidFinish:)
name:MPMoviePlayerPlaybackDidFinishNotification
object:moviePlayer];
moviePlayer.shouldAutoplay = NO;
[moviePlayer prepareToPlay];
}
-(void)moviePlaybackDidFinish:(NSNotification *)notification {
// your custom code which you want to play after the player did finish playing
}

Resources