防止MPMoviePlayerController中断设备的主音频

时间:2014-02-27 15:43:42

标签: ios mpmovieplayercontroller

我使用MPMoviePlayerController为我的应用程序添加了一个介绍性视频。视频按预期播放。但是,视频没有 - 也不应该 - 有声音但是,如果用户正在他们的设备上听音乐(例如),然后打开我的应用程序,音乐会在我的视频开始播放时停止播放。由于我的视频没有声音,我希望我的视频播放不会中断设备上的主音频。

我查看了MPMoviePlayerController类,并没有看到任何线索。有没有办法做到这一点?这是我的代码:

- (void)setUpVideoPlayer
{

  NSString *videoFilePath = [[NSBundle mainBundle] pathForResource:@"introVideo" ofType:@"MP4"];
  NSURL *videoUrl =  [NSURL fileURLWithPath:videoFilePath];
  MPMoviePlayerController *player = [[MPMoviePlayerController alloc]initWithContentURL:videoUrl];

  player.backgroundView.hidden = YES;
  player.movieSourceType = MPMovieSourceTypeFile;

  [player prepareToPlay];

  [player setShouldAutoplay:YES];
  [player setRepeatMode:MPMovieRepeatModeOne];
  [player setFullscreen:YES];
  [player setControlStyle:MPMovieControlStyleNone];
  [player setScalingMode:MPMovieScalingModeAspectFill];
  [player play];

  player.view.translatesAutoresizingMaskIntoConstraints = NO;

  NSLayoutConstraint *playerWidth = [NSLayoutConstraint constraintWithItem:player.view attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeWidth multiplier:1.0f constant:0.0f];
  NSLayoutConstraint *playerHeight = [NSLayoutConstraint constraintWithItem:player.view attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeHeight multiplier:1.0f constant:0.0f];
  NSLayoutConstraint *playerTop = [NSLayoutConstraint constraintWithItem:player.view attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1.0f constant:0.0f];
  NSLayoutConstraint *playerLeft = [NSLayoutConstraint constraintWithItem:player.view attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1.0f constant:0.0f];

  [self.view addSubview:player.view];
  [self.view addConstraints:@[playerWidth, playerHeight, playerTop, playerLeft]];

  _player = player;

}

1 个答案:

答案 0 :(得分:14)

回答了我自己的问题:

#import <AVFoundation/AVAudioSession.h>
#import <AudioToolbox/AudioSession.h>

- (void)viewDidLoad
{
  [super viewDidLoad];

  [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryAmbient error: nil];

  //do other stuff
}