iOS 播放没有音频会话的视频

问题描述 投票:0回答:4

我正在尝试使用

MPMoviePlayerController
AVPlayer
在我的应用程序中播放短视频。问题是(因为我的视频没有任何声音)我不想干扰其他应用程序在后台播放的声音。我试着玩
AVAudioSession

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

但我没有运气。视频一开始播放,背景音乐就停止了。我什至尝试将音频会话设置为非活动状态:

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

但在这种情况下,声音会停止半秒钟,然后继续播放,视频播放器也会停止播放。有什么办法可以实现我想要做的事情吗?谢谢。

ios mpmovieplayercontroller avplayer avaudiosession
4个回答
4
投票

我认为这与您不再相关,但可能与其他人相关。

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

例子:

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

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


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

所以他们停止播放并在中断结束后开始播放。 (用于来电等)


0
投票

设置共享类别时有“与他人混合”选项

AVAudioSession

try? AVAudioSession.sharedInstance().setCategory(.ambient,
                                                 mode: .moviePlayback,
                                                 options: [.mixWithOthers])

默认为

AVAudioSession.Category.soloAmbient
,说明关闭其他应用程序的音频。


-2
投票

很好的答案!对于那些感兴趣的人来说,这是一个Swift 5 转换。

try? AVAudioSession.sharedInstance().setCategory(.ambient)
© www.soinside.com 2019 - 2024. All rights reserved.