首页 > 如何让音效在应用处于后台状态时自动停止

如何让音效在应用处于后台状态时自动停止

我现在在用 AVAduioPlayer 在后台播放音效(白噪音软件),然后应用是允许用户设置播放时间的,但是当应用在后台时,NSTimer 的回调函数是不会被调用的,这个时候我该如何停止音效呢?

代码:

- (void)play:(NSString *)soundName withTime:(NSNumber *)time
{
  NSURL *soundUrl = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/sounds/%@.m4a", [[NSBundle mainBundle] resourcePath], soundName]];
  _audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:nil];
  _audioPlayer.numberOfLoops = -1;
  [_audioPlayer play];

  [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:nil];
  [[AVAudioSession sharedInstance] setActive:YES error:nil];

  [self scheduleStopSound:time]; // how to implement it.
}

我印象中可以直接配置出这个效果吧。

试试[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategorySoloAmbient error:nil];,看可以吗?


以下是解决办法:

objectivec// App将要进入后台,实现 applicationDidEnterBackgroundNotification ,做处理
[NSNotificationCenter.defaultCenter addObserver:self selector:@selector(applicationDidEnterBackgroundNotification) name:UIApplicationDidEnterBackgroundNotification object:nil];

// App将要回到前台,实现 applicationWillEnterForegroundNotification ,做处理
[NSNotificationCenter.defaultCenter addObserver:self selector:@selector(applicationWillEnterForegroundNotification) name:UIApplicationWillEnterForegroundNotification object:nil];

你还可以在AppDelegate里面实现对应的方法来做处理,但是不建议你这么做,因为这样会让AppDelegate里面堆积太多要处理的东西,通过系统通知进行处理的好处是可以把这些耦合解开。

【热门文章】
【热门文章】