2014-10-20 229 views
1

我想在我的应用中使用MPMoviePlayerControllerAVPlayer播放短视频。问题是(因为我的视频没有任何声音),我不想干扰其他应用在后台播放的声音。我试图玩AVAudioSessioniOS无视频会话播放视频

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

但我没有运气。只要视频开始播放,背景音乐就会停止。我甚至tryied设置音频会话不活动:

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

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

+0

你的视频中只有视频编解码器吗?检查您的视频文件的信息。 (应该只是编解码器:例如H.264而不是H.264 AAC) – kabarga 2014-10-20 22:09:20

+0

唯一的编解码器是H.264 – Teo 2014-10-20 22:19:41

回答

0

您是否正在使用音乐bkg应用进行测试? 如果没有,那么可能的答案是,大多数的音乐应用程序包含:

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

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

1

我认为这与您无关,但可能与其他人有关。

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

实施例:

- (void)initPlayer { 

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

    // some init logic 
    // e.g: 
    // 
    // _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; 
} 

P.S.我假设,FB应用程序正在做类似的事情:当视频开始播放静音时,它不会中断其他应用程序的音频,但是当用户按下视频时,它会以全屏方式播放声音,此时将会有该视频的活动音频会话,所有其他应用程序将停止播放音频。

+0

谢谢!就是我刚才在找的东西! – onnoweb 2016-07-07 22:48:41