我知道有很多关于 SOF 的问题,但这是“最新”的问题。问题是,我正在尝试创建应用程序并发出警报,而且我知道有一些警报应用程序可以完美地(以某种方式)运行,即使该应用程序没有运行并且在后台也是如此。
我的问题是:您如何在您的应用已经在后台播放声音?
UILocalNotification 很棒,但是你只会在用户已经点击你的通知后得到 application:(_:didReceiveLocalNotification:)
,所以使用 AVAudioPlayer 播放声音是行不通的,我想无论用户是否点击它,都可以播放声音。当然,Required background modes: App plays audio or streams audio/video using AirPlay
in info.plist
已设置。一旦音乐开始播放,即使我进入后台,它也会继续播放。
我不想使用 UILocalNotificaation 声音,因为它被限制在 30 秒内并且只能播放与应用程序捆绑在一起的声音。
有什么见解吗?想法??
示例代码:
var notif = UILocalNotification()
notif.fireDate = self.datePicker.date
notif.alertBody = "test"
UIApplication.sharedApplication().scheduleLocalNotification(notif)
上面的代码在用户选择报警并点击保存时被调用。
这是 AppDelegate 中发生的事情:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
NSLog("launched")
application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Sound | UIUserNotificationType.Alert |
UIUserNotificationType.Badge, categories: nil
))
AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil)
AVAudioSession.sharedInstance().setActive(true, error: nil)
self.sound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("sound", ofType: "caf"))
self.audioPlayer = AVAudioPlayer(contentsOfURL: sound, error: nil)
return true
}
func application(application: UIApplication!, didReceiveLocalNotification notification: UILocalNotification!){
audioPlayer.play()
NSLog("received local notif")
}
顺便说一句,您需要持有对 AVAudioPlayer
的强引用,这样它就不会被释放,并且 audioplayer.play()
也不会执行任何操作。 ..
最佳答案
最后,我设法用 NSTimer 做到了。
func applicationWillResignActive(application: UIApplication) {
var timer = NSTimer(fireDate: NSDate(timeIntervalSinceNow: 20), interval: 60.0, target: self, selector: Selector("playAlarm"), userInfo: nil, repeats: false)
NSRunLoop.currentRunLoop().addTimer(timer, forMode: NSDefaultRunLoopMode)
}
func playAlarm() {
self.sound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("sound", ofType: "caf"))
self.audioPlayer = AVAudioPlayer(contentsOfURL: sound, error: nil)
audioPlayer.play()
}
在其他地方,UILocalNotification 与此计时器同步,以获得良好的用户体验。
虽然我不确定这是否会通过 apple,但我看不出有任何理由不会:\
关于iOs 8,在后台开始播放声音,闹钟应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24749150/