Полноэкранный просмотр MPMoviePlayerController в iPad

Я хочу показать MPMoviePlayerController в контроллере представления и позволить пользователю переключать полноэкранный режим с помощью элементов управления по умолчанию, таких как приложение YouTube. Я использую следующий код в примере с голубыми костями:

- (void)viewDidLoad {
    [super viewDidLoad];
    self.player = [[MPMoviePlayerController alloc] init];
    self.player.contentURL = theURL;
    self.player.view.frame = self.viewForMovie.bounds;
    self.player.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self.viewForMovie addSubview:player.view];
    [self.player play];
}

Это хорошо работает, пока пользователь не сделает полноэкранный видеоролик, вращает устройство и краны на экране. Строка состояния отображается в неправильном положении, как показано на скриншоте ниже.

screenshot

Я работаю с шаблоном Tab Bar Application для iPad. Я добавил только viewDidLoad выше, переменные представления и UIView в XIB, чтобы показать проигрывателя видео.

Что я делаю неправильно?

Ответы

Ответ 1

Да, я тоже испытываю эту проблему. Это определенно является ошибкой самого MPMoviePlayerController.

Обходной путь, который я установил в своем приложении, - это просто скорректировать строку состояния при выходе из полноэкранного режима:

- (void)playerDidExitFullscreen:(NSNotification *)notification {
    MPMoviePlayerController *moviePlayer = (MPMoviePlayerController *) notification.object;

    if (moviePlayer == self.player) {
        UIApplication *app = [UIApplication sharedApplication];
        if (app.statusBarOrientation != self.interfaceOrientation) {
            [app setStatusBarOrientation:self.interfaceOrientation animated:NO];
        }
    }
}

Это не устраняет проблему в полноэкранном режиме, но потом исправляет ее.

Обратите внимание, что функция должна быть добавлена ​​к уведомлению:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playerDidExitFullscreen:) name:MPMoviePlayerDidExitFullscreenNotification object:nil];

Ответ 2

Is shouldAutorotateToInterfaceOrientation: interfaceOrientation возвращает YES для всех поддерживаемых ориентаций?

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return YES;
}

Если вы предоставили больше своего кода, это поможет.

Ответ 3

Вы используете интерфейс-интерфейс для своего пользовательского интерфейса? если это так, убедитесь, что вы указали ориентацию вида на "пейзаж" в инспекторе атрибутов вида.

Ответ 4

Имел ту же проблему, просто потратил полдня, разобрав ее. С iPad в портретной ориентации, когда я начинал видео, используя образец кода (или любой, который я мог найти в сети), видео и панель управления были отформатированы для портрета и, следовательно, повсюду на экране.

Во всяком случае, для меня работает следующее.

  /* Call the code like below:
        int iLandscape;
        if( newOrientation==UIInterfaceOrientationLandscapeLeft || newOrientation==UIInterfaceOrientationLandscapeRight )
             iLandscape=1;

        [self PlayVideo:iLandscape fullscreen:1]
    */
        //////////////////////////////////////////////////////////////////////////
        - (void)PlayVideo:(int)iLandscape fullscreen:(int)iFullScreen 
        {
            NSString *url = [[NSBundle mainBundle] pathForResource:@"myvideofile" ofType:@"m4v"];

        if( iFullScreen==0 )
        {
            MPMoviePlayerController *player2 = 
                [[MPMoviePlayerController alloc] 
                    initWithContentURL:[NSURL fileURLWithPath:url]];

            [[NSNotificationCenter defaultCenter] 
                addObserver:self
                   selector:@selector(movieFinishedCallback:)
                       name:MPMoviePlayerPlaybackDidFinishNotification
                     object:player2];

            //---play partial screen---
            player2.view.frame = CGRectMake(0, 0, m_iScreenWidth, m_iScreenHeight);
            [self addSubview:player2.view];
            //---play movie---
            [player2 play];
        }   
        else
        {
            MPMoviePlayerViewController *playerViewController = [[MPMoviePlayerViewController alloc] 
                initWithContentURL:[NSURL fileURLWithPath:url]];

            [[NSNotificationCenter defaultCenter] 
                addObserver:self
                   selector:@selector(movieFinishedCallback:)
                       name:MPMoviePlayerPlaybackDidFinishNotification
                     object:[playerViewController moviePlayer]];

            if( iLandscape )
            {
                playerViewController.view.frame = CGRectMake(0, 0, m_iScreenWidth, m_iScreenHeight);
            }
            [self addSubview:playerViewController.view];
            //play movie
            MPMoviePlayerController *player = [playerViewController moviePlayer];
            player.scalingMode=MPMovieScalingModeAspectFit;
            [player play];
        }
    }


    //////////////////////////////////////////////////////////////////////////
    - (void) movieFinishedCallback:(NSNotification*) aNotification 
    {
        MPMoviePlayerController *player = [aNotification object];
        [[NSNotificationCenter defaultCenter] removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification object:player];    
        [player autorelease];    
        [player.view removeFromSuperview];
    }

Ответ 5

Вы решили эту проблему?

[[UIApplication sharedApplication] setStatusBarOrientation:UIDeviceOrientationPortrait animated:NO];

Этот код может помочь вам.

Ответ 6

Нашел.

Была та же проблема - вот что я сделал. Я бы предложил добавить код к вашему проекту один за другим, чтобы увидеть, как он работает.

Во-первых - я помещаю вещи в портретный режим.

[[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationPortrait animated:NO];

Затем я сунул фильм вниз в строку состояния. Примечание - это предполагает, что видео имеет соотношение сторон 4x3

theVideo = [[MPMoviePlayerController alloc] initWithContentURL: [NSURL fileURLWithPath : path]];
float aspectRatio = (3.0f/4.0f);
float theMovieHeight = [self view].bounds.size.width * aspectRatio;
[[theVideo view] setFrame:(CGRectMake(0, [self view].bounds.size.height - theMovieHeight, [self view].bounds.size.width, theMovieHeight ))]; 

Затем в том месте, где запускается приложение (в моем проекте оно находится в функции didFinishLaunchingWithOptions) - в любом случае вам просто нужен доступ к объекту окна.

float aspectRatio = (3.0f/4.0f);
float theMovieHeight = self.window.bounds.size.width * aspectRatio;
float theSpaceAboveTheMovie = self.window.bounds.size.height - theMovieHeight;
float whereTheMovieShouldBeCentered = (self.window.bounds.size.height - theMovieHeight) / 2;

CGAffineTransform theTransform = CGAffineTransformMakeTranslation(0,0);

theTransform = CGAffineTransformScale(theTransform, 1.0f/aspectRatio, 1.0f/aspectRatio);
theTransform = CGAffineTransformTranslate(theTransform, -whereTheMovieShouldBeCentered, 0);
theTransform = CGAffineTransformRotate(theTransform, M_PI / 2);
theTransform = CGAffineTransformTranslate(theTransform, 0, -theSpaceAboveTheMovie);

[self.window setTransform:theTransform];

Помните, что аффинные преобразования выполняются в обратном порядке. Поэтому, если вы хотите увидеть, что делает каждое преобразование (я предлагаю вам это делать), прокомментируйте первые три

Здесь вы должны увидеть фильм и строку состояния, расположенную по центру страницы

//  theTransform = CGAffineTransformScale(theTransform, 1.0f/aspectRatio, 1.0f/aspectRatio);
//  theTransform = CGAffineTransformTranslate(theTransform, -whereTheMovieShouldBeCentered, 0);
//  theTransform = CGAffineTransformRotate(theTransform, M_PI / 2);
    theTransform = CGAffineTransformTranslate(theTransform, 0, -theSpaceAboveTheMovie);

Тогда первые два

Здесь вы должны увидеть, что фильм и строка состояния повернуты и больше не центрированы

//  theTransform = CGAffineTransformScale(theTransform, 1.0f/aspectRatio, 1.0f/aspectRatio);
//  theTransform = CGAffineTransformTranslate(theTransform, -whereTheMovieShouldBeCentered, 0);
    theTransform = CGAffineTransformRotate(theTransform, M_PI / 2);
    theTransform = CGAffineTransformTranslate(theTransform, 0, -theSpaceAboveTheMovie);

Здесь вы должны увидеть его повернутым и центрированным.

//  theTransform = CGAffineTransformScale(theTransform, 1.0f/aspectRatio, 1.0f/aspectRatio);
    theTransform = CGAffineTransformTranslate(theTransform, -whereTheMovieShouldBeCentered, 0);
    theTransform = CGAffineTransformRotate(theTransform, M_PI / 2);
    theTransform = CGAffineTransformTranslate(theTransform, 0, -theSpaceAboveTheMovie);

И с ними все, оно повернуто и полноэкранный

Вы можете загрузить мой пример кода здесь.

Ответ 7

Попробуйте это

 - (void)willEnterFullscreen:(NSNotification*)notification {
     NSLog(@"willEnterFullscreen");

    [[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationLandscapeRight animated:NO];
  }

 - (void)enteredFullscreen:(NSNotification*)notification {
     NSLog(@"enteredFullscreen");
 }

- (void)willExitFullscreen:(NSNotification*)notification {
    NSLog(@"willExitFullscreen");

    [[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationPortrait animated:NO];


}

- (void)exitedFullscreen:(NSNotification*)notification {
    NSLog(@"exitedFullscreen");

    [[NSNotificationCenter defaultCenter] removeObserver:self];
}