iOS无video会话播放video

我正尝试在我的应用程序中使用MPMoviePlayerControllerAVPlayer播放短片。 问题是(因为我的video没有任何声音),我不想干扰其他应用程序在后台播放的声音。 我试图玩AVAudioSession

 AVAudioSession *audioSession = [AVAudioSession sharedInstance]; [audioSession setCategory:AVAudioSessionCategoryAmbient withOptions:AVAudioSessionCategoryOptionMixWithOthers error:nil]; [audioSession setActive:YES error:nil]; 

但我没有运气。 只要video开始播放,背景音乐就会停止。 我什至试图设置audio会话不活动:

  [[AVAudioSession sharedInstance] setActive:NO withOptions: AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:nil]; 

但在这种情况下,声音停止半秒钟,然后恢复,video播放器停止播放。 有什么办法可以实现我想要做的? 谢谢。

我认为这不再适用于你,但可以与其他人有关。

没有什么可做的,但是这里有一些解决方法。 重点是,当初始化video播放器时,将audio会话类别设置为环境,在这种情况下,它不会中断其他应用程序中的audio会话。 然后,如果您需要“取消静音”video,则可以将audio会话类别设置为默认(独奏环境)。 它会中断其他应用程序中的audio会话,并将继续播放有声video。

例:

 - (void)initPlayer { [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient withOptions:0 error:nil]; // some init logic // eg: // // _playerItem = [AVPlayerItem playerItemWithAsset:[AVAsset assetWithURL:_URL]]; // _player = [AVPlayer playerWithPlayerItem:_playerItem]; // _playerLayer = [AVPlayerLayer playerLayerWithPlayer:_player]; // // etc. } - (void)setMuted:(BOOL)muted { if (!muted) { [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategorySoloAmbient withOptions:0 error:nil]; } self.player.muted = muted; } 

PS我认为,FB应用程序正在做类似的事情:当video开始播放静音时,它不会中断其他应用程序的audio,但是当用户按下video时,它将会全屏播放声音,此时会有活动的audio会话video,所有其他应用程序将停止播放audio。

你用你的音乐bkg应用程序testing? 如果不是那么可能的答案是,大多数音乐应用程序包含:

 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleAudioSessionInterruption:) name:AVAudioSessionInterruptionNotification object:aSession]; 

并执行如下:

 - (void) handleAudioSessionInterruption:(NSNotification*)notification { NSNumber *interruptionType = [[notification userInfo] objectForKey:AVAudioSessionInterruptionTypeKey]; .....code.... switch (interruptionType.unsignedIntegerValue) { case AVAudioSessionInterruptionTypeBegan:{ // stop playing } break; case AVAudioSessionInterruptionTypeEnded:{ // continue playing } break; default: break; } } 

所以他们停止播放,并在中断结束时启动它。 (来电等)