【问题标题】:Playing Audio in Background at a certain time在特定时间在后台播放音频
【发布时间】:2020-05-20 11:08:08
【问题描述】:

使用 Swift5.2、Xcode11.4 和 iOS13.4,

我尝试在未来的某个时间运行音频。

另外,App处于后台模式(App完全关闭)。

必须设置 Audiosession 以保持应用响应,并且音频声音应在最长 1 年的延迟时间开始。

我试过了:

A) 添加背景模式“音频、AirPlay 和画中画”:

B) AudioSession 和 AVAudioPlayer 配置如下:

import AVKit

var audioPlayer: AVAudioPlayer?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]?)
        -> Bool {

    do {
        //set up audio session
        let audioSession = AVAudioSession.sharedInstance()
        try audioSession.setCategory(.playback, mode: .default, options: [.defaultToSpeaker, .duckOthers])
        try audioSession.setActive(true)

        // Start AVAudioPlayer
        try audioPlayer = AVAudioPlayer(contentsOf: alertSound)
        audioPlayer!.numberOfLoops = -1 // play endlessly
        audioPlayer!.prepareToPlay()
        let currentAudioTime = audioPlayer!.deviceCurrentTime
        let delayTime: TimeInterval = 20.0 // here as an example, we use 20 seconds delay
        audioPlayer!.play(atTime: currentAudioTime + delayTime) // delayTime is the time after which the audio will start
    }
    catch {
      print(error)
    }

    return true
}

.

上面的代码有两个问题:

  1. 会话类别.playback 确实会导致错误Error Domain=NSOSStatusErrorDomain Code=-50 "(null)"

  2. 只有当应用程序处于前台或后台应用程序仍处于活动状态时才会播放声音 - 但不幸的是不会在后台应用程序完全关闭时播放

这里是我的问题:

  1. 为什么 session-category .playback 在 iOS13.4 下不起作用?

  2. 为什么应用完全关闭时没有声音? (后台模式)???

  3. 仅设置背景模式标签“音频、AirPlay 和画中画”就足够了吗?或者是否需要一些代码才能完全实现后台模式?代码中是否缺少某些东西以便在完全封闭的应用程序中实现良好的未来启动?

关于问题1:

--> 我找到了解决方法并将会话类别设置为.playAndRecored - 之后错误消失

try audioSession.setCategory(.playAndRecord, mode: .default, options: [.defaultToSpeaker, .duckOthers])

问题仍然存在:为什么 .playback 不起作用? .playback.playAndRecord有什么区别?

【问题讨论】:

    标签: swift avaudioplayer avaudiosession avkit background-mode


    【解决方案1】:
    1. 为什么会话类别 .playback 在 iOS13.4 下不起作用?

    .defaultToSpeaker 选项在与.playback 一起使用时会导致该错误。我不知道为什么。如果你删除它,它应该可以工作。

    1. 为什么应用程序完全关闭时没有声音? (后台模式)???

    当应用程序被终止时,音频会话被终止。如果您想在应用程序的生命周期之外播放声音,则需要使用远程通知。关于构建闹钟应用,请参阅本文中的“推送通知方法”:

    http://andrewmarinov.com/building-an-alarm-app-on-ios/

    请注意,此方法存在局限性,主要是它需要用户在闹钟时间连接互联网才能工作。这是当前在应用程序生命周期之外设置警报的方法,而不是发送一个简单的本地通知,它对声音播放有其自身的限制,并被硬件静音开关静音。

    该链接中还有其他方法可以让您的应用保持打开状态,但它会通知用户(保持麦克风始终打开,或订阅频繁的位置更新)。

    1. 只需设置背景模式标签“音频、AirPlay 和画中画”就足够了吗?或者是否需要一些代码才能完全实现后台模式?代码中是否缺少某些内容以便在完全封闭的应用中实现良好的未来启动?

    此后台模式可防止您的应用在音频会话处于活动状态时被暂停。它不会阻止您的应用程序被杀死。一旦被杀死,您的应用在再次打开之前无法播放任何声音。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      • 2011-08-15
      相关资源
      最近更新 更多