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

 幸福的xinwangnanfei_736 发布于 2022-11-01 22:02

我现在在用 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.
}
2 个回答
  • 我印象中可以直接配置出这个效果吧。

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

    2022-11-02 19:21 回答
  • 以下是解决办法:

    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里面堆积太多要处理的东西,通过系统通知进行处理的好处是可以把这些耦合解开。

    2022-11-02 19:22 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有