我现在在用 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.
}
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
以下是解决办法:
你还可以在
AppDelegate里面实现对应的方法来做处理,但是不建议你这么做,因为这样会让AppDelegate里面堆积太多要处理的东西,通过系统通知进行处理的好处是可以把这些耦合解开。我印象中可以直接配置出这个效果吧。
试试
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategorySoloAmbient error:nil];,看可以吗?