While a movie is playing, if I change my contentURL the movie stops playing and the view is removed.
I've tried the solution here but it still doesn't work.
Here's my code to play the movie:
- (void) playMovie:(NSURL *)moviePath{
theMovie = [[MPMoviePlayerController alloc] initWithContentURL: moviePath];
UIView * movieView = [theMovie view];
[movieView setFrame: CGRectMake(0, 0, 480, 320)];
[[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationNone];
[[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationLandscapeRight animated:NO];
CGAffineTransform landscapeTransform;
landscapeTransform = CGAffineTransformMakeRotation(degreesToRadian(90));
landscapeTransform = CGAffineTransformTranslate(landscapeTransform, 80, 80);
[movieView setTransform: landscapeTransform];
self.theMovie.scalingMode = MPMovieScalingModeAspectFit;
self.theMovie.fullscreen = TRUE;
self.theMovie.controlStyle = MPMovieControlStyleNone;
[self performSelector:#selector(showCtrlsOnTouch) withObject:NULL afterDelay:0.1];
[self.theMovie prepareToPlay];
int a = currentMovie;
int b = [self.tableDataSource count] - 1;
if(a < b)
{
UIButton *nextButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
nextButton.frame = CGRectMake(360.0, 138.0, 100.0, 44.0);
[nextButton setTitle:#"Next" forState:UIControlStateNormal];
[self.theMovie.view addSubview:nextButton];
[nextButton addTarget:self action:#selector(playNextMovie:) forControlEvents:UIControlEventTouchUpInside];
}
if(currentMovie > 0)
{
UIButton *previousButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
previousButton.frame = CGRectMake(40.0, 138.0, 100.0, 44.0);
[previousButton setTitle:#"Prev" forState:UIControlStateNormal];
[self.theMovie.view addSubview:previousButton];
[previousButton addTarget:self action:#selector(playPreviousMovie:) forControlEvents:UIControlEventTouchUpInside];
}
[[[UIApplication sharedApplication] keyWindow] addSubview: movieView];
[[NSNotificationCenter defaultCenter] addObserver: self
selector: #selector(movieFinishedCallback:)
name: MPMoviePlayerPlaybackDidFinishNotification
object: self.theMovie];}
And here's my code to switch the movie:
- (void) playNextMovie:(id) sender{
currentMovie++;
NSDictionary *dictionary = [self.tableDataSource objectAtIndex:currentMovie];
NSString *videoString = [NSString stringWithFormat:#"%#", [dictionary objectForKey:#"videoFile"]];
NSString *videoPath = [[NSBundle mainBundle] pathForResource:videoString ofType:#"m4v"];
NSLog(#"Video Path: %#", videoPath);
NSURL *moviePath = [NSURL fileURLWithPath: videoPath];
self.theMovie.contentURL = moviePath;
[self.theMovie prepareToPlay];}
Thanks for any help.
It is totally normal for the player to stop playing once a new contentURL is supplied.
The MPMoviePlayerController.view however is usually not being removed automatically. I am assuming that you forgot about one of your notification handlers doing something like that for you.
Related
At first, sorry for my bad English, I'm just learning it. Im relatively new at Objective-C and I'm using FBConnect bundle to link my app to Facebook. All it's working correctly, but when I click a link into the UIWebView (the Facebook login button, for example), my UIWebView gets fullscreen and hides my close button (a little 'x' button in the top right of the UIWebView, called here "_closeButton").
Here's the code:
The "init" method:
- (id)init {
if ((self = [super initWithFrame:CGRectZero])) {
_delegate = nil;
_loadingURL = nil;
_showingKeyboard = NO;
self.backgroundColor = [UIColor clearColor];
self.autoresizesSubviews = NO;
//self.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
self.contentMode = UIViewContentModeRedraw;
_webView = [[UIWebView alloc] initWithFrame:CGRectMake(kPadding, kPadding, 480, 480)];
_webView.delegate = self;
//_webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
[self addSubview:_webView];
//UIImage* closeImage = [UIImage imageNamed:#"FBDialog.bundle/images/close.png"];
UIImage* closeImage = [UIImage imageNamed:#"close"];
UIColor* color = [UIColor colorWithRed:255.0/255 green:/*184.0*/0.0/255 blue:/*216.0*/0.0/255 alpha:1];
_closeButton = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
[_closeButton setImage:closeImage forState:UIControlStateNormal];
[_closeButton setTitleColor:color forState:UIControlStateNormal];
[_closeButton setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
[_closeButton addTarget:self action:#selector(cancel)
forControlEvents:UIControlEventTouchUpInside];
// To be compatible with OS 2.x
#if __IPHONE_OS_VERSION_MAX_ALLOWED <= __IPHONE_2_2
_closeButton.font = [UIFont boldSystemFontOfSize:12];
#else
_closeButton.titleLabel.font = [UIFont boldSystemFontOfSize:12];
#endif
_closeButton.showsTouchWhenHighlighted = YES;
_closeButton.autoresizingMask = UIViewAutoresizingFlexibleRightMargin
| UIViewAutoresizingFlexibleBottomMargin;
[self addSubview:_closeButton];
NSLog(#"close");
_spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:
UIActivityIndicatorViewStyleWhiteLarge];
_spinner.autoresizingMask =
UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin
| UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
[self addSubview:_spinner];
_modalBackgroundView = [[UIView alloc] init];
}
return self;
}
The delegate of the WebView (I suspect here's where I need to do the trick)
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request
navigationType:(UIWebViewNavigationType)navigationType {
NSURL* url = request.URL;
if ([url.scheme isEqualToString:#"fbconnect"]) {
if ([[url.resourceSpecifier substringToIndex:8] isEqualToString:#"//cancel"]) {
NSString * errorCode = [self getStringFromUrl:[url absoluteString] needle:#"error_code="];
NSString * errorStr = [self getStringFromUrl:[url absoluteString] needle:#"error_msg="];
if (errorCode) {
NSDictionary * errorData = [NSDictionary dictionaryWithObject:errorStr forKey:#"error_msg"];
NSError * error = [NSError errorWithDomain:#"facebookErrDomain"
code:[errorCode intValue]
userInfo:errorData];
[self dismissWithError:error animated:YES];
} else {
[self dialogDidCancel:url];
}
} else {
[self dialogDidSucceed:url];
}
return NO;
} else if ([_loadingURL isEqual:url]) {
return YES;
} else if (navigationType == UIWebViewNavigationTypeLinkClicked) {
if ([_delegate respondsToSelector:#selector(dialog:shouldOpenURLInExternalBrowser:)]) {
if (![_delegate dialog:self shouldOpenURLInExternalBrowser:url]) {
return NO;
}
}
[[UIApplication sharedApplication] openURL:request.URL];
return NO;
} else {
return YES;
}
}
And the show method (called when I need to show the Web View)
- (void)show {
NSLog(#"Cuantas veces me ves?");
[self load];
[self sizeToFitOrientation:NO];
CGFloat innerWidth = self.frame.size.width - (kBorderWidth+1)*2;
[_closeButton sizeToFit];
_closeButton.frame = CGRectMake(
2,
2,
29,
29);
_webView.frame = CGRectMake(
kBorderWidth+1,
kBorderWidth+1,
innerWidth,
self.frame.size.height - (1 + kBorderWidth*2));
[_spinner sizeToFit];
[_spinner startAnimating];
_spinner.center = _webView.center;
UIWindow* window = [UIApplication sharedApplication].keyWindow;
if (!window) {
window = [[UIApplication sharedApplication].windows objectAtIndex:0];
}
_modalBackgroundView.frame = window.frame;
[_modalBackgroundView addSubview:self];
[window addSubview:_modalBackgroundView];
[window addSubview:self];
[self dialogWillAppear];
self.transform = CGAffineTransformScale([self transformForOrientation], 0.001, 0.001);
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:kTransitionDuration/1.5];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:#selector(bounce1AnimationStopped)];
self.transform = CGAffineTransformScale([self transformForOrientation], 1.1, 1.1);
[UIView commitAnimations];
[self addObservers];
}
Googling the problem, I found that this could be the Default behaviour of the UIWebView. How can I change it to make all my WebViews of the same size than the first one?
Thanks in advance!
== EDIT ==
Still don't know why is my UIWebView acting like this, or how to solve it, but since the code is part of the FBConnect Bundle, I suppose I shouldn't edit it too much. I just created programmatically a new close button on the top and that's all. But I'll let the question open if someone knows how to solve it. Thanks to Leo Natan for his help.
I need to quit the MPMoviePlayerController programmatically while playing, instead of pressing done button. Is it possible. Is there any way to simulate Done button click?
i have one trick for you. you can take the mpmovieplayer on uiview and then remove the uiview after stoping the player
In ViewController.h
MPMoviePlayerController *moviePlayerController;
UIView *view1;
-(IBAction)cancelPlay:(id)sender;
In ViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *filepath = [[NSBundle mainBundle] pathForResource:#"try" ofType:#"mp4"];
NSURL *fileURL = [NSURL fileURLWithPath:filepath];
view1=[[UIView alloc]initWithFrame:CGRectMake(0, 10, 320, 300)];
view1.backgroundColor=[UIColor blueColor];
[self.view addSubview:view1];
moviePlayerController = [[MPMoviePlayerController alloc] initWithContentURL:fileURL];
[moviePlayerController.view setFrame:CGRectMake(0, 10, 320,300)];
[view1 addSubview:moviePlayerController.view];
moviePlayerController.fullscreen = YES;
moviePlayerController.controlStyle=MPMovieControlStyleEmbedded;
[moviePlayerController play];
}
-(IBAction)cancelPlay:(id)sender{
[moviePlayerController stop];
[view1 removeFromSuperview];
}
In this application starting onwards Portrait mode.
.
code snippet
NSInteger heightOne;
NSInteger heightTwo;
NSInteger imgV;
CGRect Bounds = [[UIScreen mainScreen] bounds];
if (Bounds.size.height == 568) {
// code for 4-inch screen
heightOne = 480+38;
heightTwo = 240+38;//370
imgV = 360;
} else {
// code for 3.5-inch screen
heightOne = 480;
heightTwo = 240;//330
imgV = 310;
}
UIView *firstView = [[UIView alloc] initWithFrame:CGRectMake(00, 00,320,heightOne)];
firstView.opaque = NO;
firstView.tag = 1000;
firstView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5f];
[self.view addSubview:firstView];
UIImageView *img = [[UIImageView alloc]initWithFrame:CGRectMake(250,imgV,50,50)];
img.image = [UIImage imageNamed:#"Zoom.jpg"];
[firstView addSubview:img];
UIView *secondView= [[UIView alloc] initWithFrame:CGRectMake(0,0,320,heightOne)];
[secondView setBackgroundColor:[UIColor clearColor]];
[firstView addSubview:secondView];
UIView *thirdView = [[UIView alloc] initWithFrame:CGRectMake(15,60,290,heightTwo)];//30
[thirdView setBackgroundColor:[UIColor whiteColor]];
thirdView.layer.cornerRadius = 2.0f;
thirdView.layer.borderWidth = 4.0f;
thirdView.layer.borderColor = [UIColor colorWithRed:0.0/255.0 green:100.0/255.0 blue:0.0/255.0 alpha:1.0].CGColor;
[secondView insertSubview:thirdView atIndex:0];
///////////////////////////// Creating custom close button ////////////////////////////////
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setFrame:CGRectMake(287,48,30,30)];//24
[button setBackgroundImage:[UIImage imageNamed:#"Close-Gr.png"] forState:UIControlStateNormal];
[button addTarget:self action:#selector(dismissOverViewController) forControlEvents:UIControlEventTouchUpInside];
button.backgroundColor = [UIColor clearColor];
[secondView insertSubview:button aboveSubview:thirdView];
secondView.frame = CGRectMake(0,0,320,480);
[UIView animateWithDuration:0.3
animations:^{
secondView.frame = CGRectMake(0,0,320,480);
}];
[thirdView setBackgroundColor:[UIColor grayColor]];
}
here i need only popup rotation .Any Ref link or suggestion ,it's really appreciated.
Return NO from
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
Handle device rotation via Local Notifications :-
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(didRotate:)
name:UIDeviceOrientationDidChangeNotification
object:nil];
And rotate the view as you want :-
self.theView.transform = CGAffineTransformIdentity;
self.theView.transform = CGAffineTransformMakeRotation(degreesToRadians(-90));
May this help you.
Please register for rotation notifications in viewdidlod
(void)viewDidLoad
{
UIInterfaceOrientation currentOrientation = [[UIApplication sharedApplication] statusBarOrientation];
if (currentOrientation == UIInterfaceOrientationLandscapeLeft || currentOrientation == UIInterfaceOrientationLandscapeRight)
[self willRotateToLandscape];
else
[self willRotateToPortrait];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(willRotateToLandscape) name:#"Interface will rotate to landscape" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(willRotateToPortrait) name:#"Interface will rotate to portrait" object:nil];
}
//then adjust the popup view size in the following functions.
- (void)willRotateToLandscape
{
}
- (void)willRotateToPortrait
{
}
How can I resize the MPMoviePlayerController dynamically to fix all the size of screens for iPhone/iPad (both portrait & landscape)?
this is my code:
- (void)viewDidLoad
{
[super viewDidLoad];
UIBarButtonItem *about = [[UIBarButtonItem alloc] initWithTitle:#"About" style:UIBarButtonItemStyleDone target:self action:#selector(openPopup)];
self.navigationItem.leftBarButtonItem = about;
NSURL *streamURL = [NSURL URLWithString:#"http:/streamUrl/playlist.m3u8"];
_streamPlayer = [[MPMoviePlayerController alloc] initWithContentURL:streamURL];
self.streamPlayer.controlStyle = MPMovieControlStyleEmbedded;
[self.view addSubview: self.streamPlayer.view];
[self.streamPlayer play];
}
I also tried to add
[self.streamPlayer.view setFrame:self.view.bounds];
but this makes the video is not fix to screen as shown in screenshot
How can I make it fix all screens of all different devices?
Thanks in advance.
The best solution I found is to use the following
CGFloat width = [UIScreen mainScreen].bounds.size.width;
CGFloat height = [UIScreen mainScreen].bounds.size.height;
[self.streamPlayer.view setFrame:CGRectMake(10, 10 ,height-20, width-70)];
i solved this problem in ios 5
as:
AvPlayerLayer *avPlayerLayer =[[AVPlayerLayer alloc]init];
avPlayerLayer = [[AVPlayerLayer playerLayerWithPlayer:avPlayer] retain];
avPlayerLayer.frame = self.playerView.layer.bounds;
avPlayerLayer.transform = CATransform3DMakeRotation(M_PI / 2.0, 0, 0, 1);
[self.playerView.layer addSublayer:avPlayerLayer];
here is avPlayerLayer.transform you can set it in any direction .
MPMoviePlayerViewController *moviePlayerViewController = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL fileURLWithPath:contentURL]];
if (moviePlayerViewController) {
[self presentMoviePlayerViewControllerAnimated:moviePlayerViewController];
[moviePlayerViewController.moviePlayer setMovieSourceType:MPMovieSourceTypeFile];
if ([moviePlayerViewController.moviePlayer respondsToSelector:#selector(setAllowsAirPlay:)]) {
[moviePlayerViewController.moviePlayer setAllowsAirPlay:YES];
}
[[NSNotificationCenter defaultCenter] addObserverForName:MPMoviePlayerPlaybackDidFinishNotification object:moviePlayerViewController queue:nil usingBlock:^(NSNotification *notification) {
[[NSNotificationCenter defaultCenter] removeObserver:self];
[self dismissMoviePlayerViewControllerAnimated];
}];
[moviePlayerViewController.moviePlayer play];
}
I have an iphone app that displays images and plays audio selected from a main menu.
The user clicks on a button to select the image/audio combo they want. The code to switch the views with animation works fine.
All of the code to display the image, play, pause, scrub, and stop the audio while in the new view works fine too.
However, when the users clicks the Main Menu button I want the playing audio to stop. I am using viewWillDisappear:(BOOL)animated to call the stop method:
-(void)viewWillDisappear:(BOOL)animated {
audioPlayer.stop;
[super viewWillDisappear: animated];}
This code doesn't stop the sound when the user switches back to the main menu view. Is there a better way to do this? Am I doing something wrong?
Here is the code from the entire class where the snippet above resides:
#import "twelthPoem.h"
UIImageView *largeImageView;
#implementation twelthPoem
-(void)resetControls
{
audioPlayer.currentTime = 0;
scrubber.value = 0;
[playButton setImage:[UIImage imageNamed:#"play_HL.png"]
forState:UIControlStateNormal];
}
-(void)play:(id)sender {
if (! audioPlayer.playing) {
audioPlayer.play;
[playButton setImage:[UIImage imageNamed:#"pauseHL.png"] forState:UIControlStateNormal];
}
else {
audioPlayer.pause;
[playButton setImage:[UIImage imageNamed:#"play_HL.png"] forState:UIControlStateNormal];
}
[self becomeFirstResponder];
}
-(void)stop:(id)sender {
audioPlayer.stop;
[self resetControls];
}
-(void)changeVolume:(id)sender {
audioPlayer.volume = volume.value;
[self becomeFirstResponder];
}
-(void)scrub:(id)sender {
if (audioPlayer.playing) {
audioPlayer.pause;
audioPlayer.currentTime = scrubber.value;
audioPlayer.play;
}
else
audioPlayer.currentTime = scrubber.value;
[self becomeFirstResponder];
}
-(void)createControls {
//play/pause button
playButton = [UIButton buttonWithType:UIButtonTypeCustom];
[playButton setFrame:CGRectMake(60,405,80,20)];
[playButton setImage:[UIImage imageNamed:#"play_HL.png"] forState:UIControlStateNormal];
[playButton addTarget:self action:#selector(play:)
forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:playButton];
//stop button
stopButton = [UIButton buttonWithType:UIButtonTypeCustom];
[stopButton setFrame:CGRectMake(180,405,80,20)];
[stopButton setImage:[UIImage imageNamed:#"stopHL.png"] forState:UIControlStateNormal];
[stopButton addTarget:self action:#selector(stop:)
forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:stopButton];
//volume control
volume = [[UISlider alloc] initWithFrame:CGRectMake(10,445,145,20)];
[volume addTarget:self action:#selector(changeVolume:)
forControlEvents:UIControlEventValueChanged];
volume.minimumValue = 0.0;
volume.maximumValue = 1.0;
volume.value = audioPlayer.volume;
volume.continuous = YES;
[self.view addSubview:volume];
//scrubber control
scrubber = [[UISlider alloc] initWithFrame:CGRectMake(165,445,145,20)];
[scrubber addTarget:self action:#selector(scrub:)
forControlEvents:UIControlEventValueChanged];
scrubber.minimumValue = 0.0;
scrubber.maximumValue = audioPlayer.duration;
scrubber.value = audioPlayer.currentTime;
scrubber.continuous = NO;
[self.view addSubview:scrubber];
}
- (void)remoteControlReceivedWithEvent:(UIEvent *)event {
switch (event.subtype)
{
case UIEventSubtypeRemoteControlTogglePlayPause:
[self play:nil];
break;
case UIEventSubtypeRemoteControlNextTrack:
//do nothing
break;
case UIEventSubtypeRemoteControlPreviousTrack:
//do nothing
break;
}
}
- (BOOL)canBecomeFirstResponder {
return YES;
}
-(void)viewDidLoad {
//for scrolling the image
[super viewDidLoad];
CGRect scrollFrame = CGRectMake(0,40,320,350);
UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:scrollFrame];
scrollView.minimumZoomScale = 1.0;
scrollView.maximumZoomScale = 1.5;
scrollView.delegate = self;
UIImage *bigImage = [UIImage imageNamed:#"birches.png"];
largeImageView = [[UIImageView alloc] initWithImage:bigImage];
[scrollView addSubview:largeImageView];
scrollView.contentSize = largeImageView.frame.size; //important!
[self.view addSubview:scrollView];
[scrollView release];
//for playing the recording
NSString *filePath = [[[NSBundle mainBundle] resourcePath]
stringByAppendingPathComponent:#"birches_final_mp3.mp3"];
NSURL *fileURL = [NSURL fileURLWithPath:filePath];
NSError *error = nil;
OSStatus status = AudioSessionInitialize(NULL, NULL, NULL, NULL);
UInt32 sessionCategory = kAudioSessionCategory_MediaPlayback;
status = AudioSessionSetProperty (kAudioSessionProperty_AudioCategory,
sizeof (sessionCategory),
&sessionCategory);
AudioSessionSetActive(YES);
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL
error:&error];
if (error )
NSLog(#"An error occurred: %#",error);
else
{
audioPlayer.volume = 0.3;
[audioPlayer prepareToPlay];
[self createControls];
}
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
}
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
return largeImageView;
}
- (void)audioPlayerBeginInterruption:(AVAudioPlayer *)player
{
interrupted = audioPlayer.playing;
}
- (void)audioPlayerEndInterruption:(AVAudioPlayer *)player
{
if (interrupted)
audioPlayer.play;
}
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player
successfully:(BOOL)flag
{
[self resetControls];
}
-(void)viewWillDisappear:(BOOL)animated {
audioPlayer.stop;
[super viewWillDisappear: animated];
}
- (void)dealloc {
[[UIApplication sharedApplication] endReceivingRemoteControlEvents];
[scrubber release];
[volume release];
[audioPlayer release];
[super dealloc];
}
#end
You call methods in objective-c using the following syntax.
[audioPlayer stop];
audioPlayer.stop will not work.
Same goes for other places as well.
audioPlayer.stop will not work mostly because it needs an expression after it, e.g. audioPlayer.stop = //expression, stop is a bool, so you can say audioPlayer.stop = YES; or [audioPlayer stop];