【问题标题】:iOs 8, start playing sound when in the background, alarm clock appiOS 8,在后台开始播放声音,闹钟应用
【发布时间】:2014-09-05 02:44:33
【问题描述】:

我知道关于 SOF 有很多问题,但这是“最新”的问题。问题是,我正在尝试创建警报应用程序,并且我知道有一个警报应用程序可以完美运行(不知何故),即使应用程序没有运行并且在后台。

我的问题是:您的应用已经在后台后如何开始播放声音?

UILocalNotification 很棒,但您只会在用户点击您的通知后获得application:(_:didReceiveLocalNotification:),因此使用 AVAudioPlayer 播放声音不起作用,无论用户点击或不点击它,我都想播放声音不。当然,Required background modes: App plays audio or streams audio/video using AirPlay 中的 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() 不会做任何事情...

【问题讨论】:

  • 如果你的应用在后台,didreceivelocalnotification 应该在通知触发后被调用。也许你可以把你的代码放在那里播放声音。
  • 我尝试了很多次,它没有,它只有在用户实际点击通知后才会被触发。无论如何我都会编辑我的问题。

标签: ios audio swift alarm


【解决方案1】:

最后,我设法用 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 与此计时器同步,以获得良好的用户体验。

虽然我不确定这是否会通过苹果,但我看不出有什么理由不会:\

【讨论】:

  • 那么,您可以通过这段代码在应用处于后台时开始播放声音吗?
  • 是的,你可以,试试看,它对我有用...尚未将应用发布到商店,很想知道是否有人可以确认这一点..
  • 我不知道为什么它会起作用。如果应用程序在后台运行,它通常会在几分钟后暂停。因此,如果应用处于挂起状态,计时器不会触发 playAlarm()。
  • 有没有人尝试过并获得苹果的认可?
  • 我相信你的应用在杀死你的应用之前有 180 秒的时间来完成任务。该计时器在该时间段结束之前触发,因此它可以工作。我不相信它会在那段时间之后起作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多