13

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

- (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 приложений для IPad. Я только добавил viewDidLoad выше, переменные представления и UIView в XIB, чтобы показать проигрывателя фильмов.

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

+0

Я испытываю тот же вопрос. По-прежнему нет обходного пути? – samvermette

+0

Я тоже. Кто-нибудь получил эту работу? – V1ru8

+0

Получили ли вы ответ? – Jingwei

ответ

2

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

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

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

+0

Да. Единственным кодом, который я добавил в проект, является viewDidLoad выше и, конечно, viewForMovie в XIB. Это приложение Tab Bar для iPad. – hpique

1

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

+0

Теперь он не работает в другой ориентации. – hpique

1

Если бы та же проблема, просто потратил полдня, разобрав ее. С 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]; 
    } 
0

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

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

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

3

Да, я тоже испытываю эту проблему. Это определенно является ошибкой самого 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]; 
0

Нашел.

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

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

[[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); 

И с ними все, что вращается и полноэкранным

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

0

Попробуйте

- (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]; 
} 
Смежные вопросы