首页 > 解决方案 > iPhone 锁定时没有声音 (Swift)

问题描述

该应用程序应在特定时间启动声音。要选择我使用本地通知的具体时间。是否到了特定时间并且应用程序位于前台,声音开始播放,即使我关闭应用程序(后台)或锁定我的 iPhone,声音也会继续播放。到现在为止还挺好。现在我想要:是否到了特定时间并且应用程序已经在后台或iPhone被锁定,它应该仍然启动声音。为了实现这一点,我打开了Background Modes电源,但没有任何改变。我添加mixWithOthers到我的代码中,仍然没有任何反应。还有其他建议吗?

import AVFoundation

var player: AVAudioPlayer?

func playSound() {
    guard let url = Bundle.main.url(forResource: "NameOfFile", withExtension: "mp3") else { return }

    do {
        try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback, mode: .default, options: AVAudioSession.CategoryOptions.mixWithOthers)
        try AVAudioSession.sharedInstance().setActive(true)

        player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)

        guard let player = player else { return }

        player.play()
        print("Start...")
    } catch let error {
        print(error.localizedDescription)
    }
}

背景模式:截图

这个问题不是重复的。我正在寻找一种解决方案来在 iPhone已经锁定/应用程序在声音开始之前处于后台时启动声音。另一个问题是在开始后在后台继续播放音频。

标签: iosswiftxcodeavaudioplayer

解决方案


你不能做你想做的事。如果您的应用程序在后台运行超过 3 分钟,您的应用程序将被挂起并且不会获得任何 CPU 时间。

您可以安排本地通知。当它触发时,系统可以选择播放保存在您的应用程序包中的声音或系统通知声音,然后点亮屏幕并显示一条通知,要求用户打开您的应用程序。在用户决定接受通知之前,您不会被呼叫。


推荐阅读