来电后AV播放器恢复正常

时间:2013-12-23 04:03:07

标签: ios ios7 avplayer avplayerlayer

我正在使用AVPlayer进行音乐播放。我的问题是,在来电后,播放器将无法恢复。来电时如何处理?

6 个答案:

答案 0 :(得分:55)

从iOS 6开始,您必须处理AVAudioSessionInterruptionNotificationAVAudioSessionMediaServicesWereResetNotification,在此之前您必须使用委托方法。

首先,您应该调用AVAudioSession单例并将其配置为您想要的用途。

例如:

AVAudioSession *aSession = [AVAudioSession sharedInstance];
[aSession setCategory:AVAudioSessionCategoryPlayback
          withOptions:AVAudioSessionCategoryOptionAllowBluetooth 
                error:&error];
[aSession setMode:AVAudioSessionModeDefault error:&error];
[aSession setActive: YES error: &error];

然后你应该实现两个方法,用于AVAudioSession将调用的通知:

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

第一个是由于来电,闹钟等而被调用的任何中断

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(handleMediaServicesReset)
                                             name:AVAudioSessionMediaServicesWereResetNotification
                                           object:aSession];

第二个如果媒体服务器因任何原因重置,您应该处理此通知以重新配置音频或进行任何内务处理。顺便说一句,通知字典将不包含任何对象。

以下是处理播放中断的示例:

- (void)handleAudioSessionInterruption:(NSNotification*)notification {

    NSNumber *interruptionType = [[notification userInfo] objectForKey:AVAudioSessionInterruptionTypeKey];
    NSNumber *interruptionOption = [[notification userInfo] objectForKey:AVAudioSessionInterruptionOptionKey];

    switch (interruptionType.unsignedIntegerValue) {
        case AVAudioSessionInterruptionTypeBegan:{
            // • Audio has stopped, already inactive
            // • Change state of UI, etc., to reflect non-playing state
        } break;
        case AVAudioSessionInterruptionTypeEnded:{
            // • Make session active
            // • Update user interface
            // • AVAudioSessionInterruptionOptionShouldResume option
            if (interruptionOption.unsignedIntegerValue == AVAudioSessionInterruptionOptionShouldResume) {
                // Here you should continue playback.
                [player play];
            }
        } break;
        default:
            break;
    }
}

请注意,当可选值为AVAudioSessionInterruptionOptionShouldResume

时,您应该恢复播放

对于其他通知,您应该注意以下事项:

- (void)handleMediaServicesReset {
// • No userInfo dictionary for this notification
// • Audio streaming objects are invalidated (zombies)
// • Handle this notification by fully reconfiguring audio
}

问候。

答案 1 :(得分:8)

AVAudioSession将在中断开始和结束时发送通知。见Handling Audio Interruptions

- (id)init
{
    if (self = [super init]) {
        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];

        NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
        [center addObserver:self selector:@selector(audioSessionInterrupted:) name:AVAudioSessionInterruptionNotification object:nil];
    }
}

- (void)audioSessionInterrupted:(NSNotification *)notification
{
    int interruptionType = [notification.userInfo[AVAudioSessionInterruptionTypeKey] intValue];
    if (interruptionType == AVAudioSessionInterruptionTypeBegan) {
        if (_state == GBPlayerStateBuffering || _state == GBPlayerStatePlaying) {
            NSLog(@"Pausing for audio session interruption");
            pausedForAudioSessionInterruption = YES;
            [self pause];
        }
    } else if (interruptionType == AVAudioSessionInterruptionTypeEnded) {
        if ([notification.userInfo[AVAudioSessionInterruptionOptionKey] intValue] == AVAudioSessionInterruptionOptionShouldResume) {
            if (pausedForAudioSessionInterruption) {
                NSLog(@"Resuming after audio session interruption");
                [self play];
            }
        }
        pausedForAudioSessionInterruption = NO;
    }
}

答案 2 :(得分:1)

在某些情况下,即使我拨打AVPlayer,我的play()也无法恢复播放。只有重新加载播放器才能帮助我解决问题:

    func interruptionNotification(_ notification: Notification) {
    guard let type = notification.userInfo?[AVAudioSessionInterruptionTypeKey] as? UInt,
      let interruption = AVAudioSessionInterruptionType(rawValue: type) else {
        return
    }
    if interruption == .ended && playerWasPlayingBeforeInterruption {
      player.replaceCurrentItem(with: AVPlayerItem(url: radioStation.url))
      play()
    }
  }

答案 3 :(得分:1)

我必须等待2秒钟才能使其正常工作。

        DispatchQueue.main.asyncAfter(deadline: .now() + 2) {

            self.player.play()
        }

整个功能:

func playerInterruption(notification: NSNotification) {

    guard let userInfo = notification.userInfo,
        let typeValue = userInfo[AVAudioSessionInterruptionTypeKey] as? UInt,
        let type = AVAudioSessionInterruptionType(rawValue: typeValue) else {
            return
    }
    if type == .began {
        // Interruption began, take appropriate actions (save state, update user interface)
        player.pause()
    }
    else if type == .ended {

        guard let optionsValue =
            userInfo[AVAudioSessionInterruptionOptionKey] as? UInt else {

                return
        }
        let options = AVAudioSessionInterruptionOptions(rawValue: optionsValue)
        if options.contains(.shouldResume) {
            // Interruption Ended - playback should resume

            DispatchQueue.main.asyncAfter(deadline: .now() + 2) {

                self.player.play()
            }

        }
    }
}

答案 4 :(得分:1)

我在“ AVAudioPlayer”控制器中遇到了同样的问题。使用“ AVAudioSession.interruptionNotification”,即使中断在后台播放,我们也可以在中断结束后继续播放音频。

    @objc func interruptionNotification(notification: Notification) {
    guard let type = notification.userInfo?[AVAudioSessionInterruptionTypeKey] as? UInt,
        let interruption = AVAudioSession.InterruptionType(rawValue: type) else {
            return
    }

    if interruption == .began{
        print("Pause audio....")
        self.player?.pause()
        do {
            try AVAudioSession.sharedInstance().setActive(false)
            print("AVAudioSession is inactive")
        } catch let error as NSError {
            print(error.localizedDescription)
        }
    }

    if interruption == .ended{
        print("Play audio....")
        do {
            try AVAudioSession.sharedInstance().setActive(true)
            print("AVAudioSession is Active again")
            self.player?.play()
        } catch let error as NSError {
            print(error.localizedDescription)
        }
    }
}

首先,您需要在中断时激活InActive AVAudioSession,并在中断结束后激活Active AVAudioSession。运行正常,请尝试!

答案 5 :(得分:1)

大家好,我读过这篇文章。希望与AVAudioSessionInterruptionNotification分享我的经验。这让我发疯。我花了一天时间找到解决方案。我尝试了上面写的所有内容,但没有任何帮助。 iOS 13.2.3。因此,出于某种原因,此通知无法与AVAudioSessionCategoryPlayback一起正常使用。对我来说,解决方法是将其替换为AVAudioSessionCategoryPlayAndRecord,然后我开始收到AVAudioSessionInterruptionTypeEnded,请参见以下示例:

-(void)setupAudioSession {

    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
    [[AVAudioSession sharedInstance] setMode:AVAudioSessionModeDefault error:nil];
    [[AVAudioSession sharedInstance] setActive:YES withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:nil];    
}

在注册您的观察者之后,像这样:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(audioSessionHandleIntrruption:) name:AVAudioSessionInterruptionNotification object:[AVAudioSession sharedInstance]];

并实际实现中断方法:

- (void)audioSessionHandleIntrruption:(NSNotification *)notification {

    NSDictionary *userInfo = notification.userInfo;
    int interruptionType = [userInfo[AVAudioSessionInterruptionTypeKey] intValue];

    if (interruptionType == AVAudioSessionInterruptionTypeBegan) {
        //Interruption begun

    } else if (interruptionType == AVAudioSessionInterruptionTypeEnded) {
        int interruptionOption = [userInfo[AVAudioSessionInterruptionOptionKey] intValue];

        BOOL shouldResumePlayback = interruptionOption == AVAudioSessionInterruptionOptionShouldResume;

        if (shouldResumePlayback) {
            //Resume playback if needed
        }
    }
}

希望这可以节省很多时间。