【问题标题】:Stop AVAudioPlayer music when the app goes to background当应用程序进入后台时停止 AVAudioPlayer 音乐
【发布时间】:2014-09-22 18:08:01
【问题描述】:

我正在开发一个小游戏,我正在使用 AVAudioPlayer 来播放游戏的背景音乐。问题是,如果用户退出应用程序而不在应用程序抽屉中关闭它(所以它在后台),音乐将不会停止。我怎样才能改变这个?感谢您的帮助!

【问题讨论】:

    标签: ios objective-c xcode sprite-kit avaudioplayer


    【解决方案1】:

    在处理 AVAudioPlayer 的 ViewController 中,将其添加到 viewDidLoad

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillResignActive:) name:UIApplicationWillResignActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillTerminate:) name:UIApplicationWillTerminateNotification object:nil];
    

    然后你添加这两种方法:

    -(void) appWillResignActive:(NSNotification*)note{
        NSLog(@"App is going to the background");
        // This is where you stop the music 
    }
    -(void) appWillTerminate:(NSNotification*)note{
        [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillResignActiveNotification object:nil];
        [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillTerminateNotification object:nil];
    
        NSLog(@"App will terminate");
    }
    

    【讨论】:

    • "resign active" 和进入后台不一样。当应用进入后台时,使用UIApplicationDidEnterBackground 而不是UIApplicationWillResignActive 得到通知。
    • 在“应用程序将终止”通知中删除观察者是没有意义的。该应用程序正在终止。这种清理在那个阶段毫无意义。
    • 没错,但我喜欢这种对称性,而且这个小练习确保我永远不会忘记删除通知。
    【解决方案2】:

    这里的快速回答是您希望将 AVAudioSession 配置为使用类别 AVAudioSessionCategorySoloAmbient。

    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategorySoloAmbient error:nil];
    

    这当然是在你激活会话之前。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多