ios - 如何让音效在应用处于后台状态时自动停止
伊谢尔伦
伊谢尔伦 2017-04-17 14:52:14
[iOS讨论组]

我现在在用 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.
}
伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

全部回复(2)
高洛峰

以下是解决办法:

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

天蓬老师

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

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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号