【问题标题】:How to resume playing audio after the camera goes away?相机消失后如何恢复播放音频?
【发布时间】:2016-10-01 12:59:39
【问题描述】:

我正在开发一个应用程序,该应用程序在使用 AVAudioPlayer 使用其他应用程序时在后台播放音频。打开相机时,音乐被静音,但 AppDelegate 中的任何方法都没有被调用,因此我无法保存歌曲的播放列表位置或播放时间。

此外,当相机关闭时,我想让应用继续播放背景音乐,但我再次没有找到任何回调方法来让我观察这种变化。

您知道如何观察摄像头确实处于活动状态以及当应用程序在后台模式下运行时摄像头被关闭吗?

【问题讨论】:

  • 相机是怎么打开的?
  • 我一直在使用向上滑动的控制面板。
  • 这会导致您的应用程序进入后台。我刚刚对其进行了测试,并调用了相应的应用委托方法。
  • 也许你的硬件不是我的。

标签: ios objective-c camera avaudioplayer observer-pattern


【解决方案1】:

我是这样解决的。

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

处理中断。

-(void)handleAudioSessionInterruption:(NSNotification*)notification
{
    //NSLog(@"%@",notification);

    NSNumber *interruptionType = [[notification userInfo] objectForKey:AVAudioSessionInterruptionTypeKey]; //1 Interuption Start, 0 Interuption Ends
    NSNumber *interruptionOption = [[notification userInfo] objectForKey:AVAudioSessionInterruptionOptionKey];

    if ([interruptionType integerValue] == AVAudioSessionInterruptionTypeBegan)
    {
        NSLog(@"Player %d interupted",playerNumber);
        // • Audio has stopped, already inactive
        // • Change state of UI, etc., to reflect non-playing state
        [self.playPauseButton setTitle:@">" forState:UIControlStateNormal];
        self.playingAudio = NO;

        return;
    }

    if ([interruptionType integerValue] == AVAudioSessionInterruptionTypeEnded)
    {
        if ([interruptionOption integerValue] == AVAudioSessionInterruptionOptionShouldResume)
        {
            NSLog(@"Player %d Resume",playerNumber);
            [self.playPauseButton setTitle:@"||" forState:UIControlStateNormal];
            self.playingAudio = YES;

            NSError *error = nil;
            AVAudioSession *aSession = [AVAudioSession sharedInstance];
            [aSession setMode:AVAudioSessionModeDefault error:&error]; //& means value at address
            [aSession setCategory:AVAudioSessionCategoryPlayback error:&error];
            //[aSession setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error:&error];
            //[aSession setMode:AVAudioSessionModeSpokenAudio error:&error];
            [aSession setActive: YES error: &error];
            [self.audioPlayer play];
        }
        // • Make session active
        // • Update user interface
        // • AVAudioSessionInterruptionOptionShouldResume option
    }

【讨论】:

    猜你喜欢
    • 2013-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-15
    • 1970-01-01
    • 1970-01-01
    • 2021-10-01
    • 2017-07-13
    相关资源
    最近更新 更多