Swift: Keep playing sounds when the device is locked

為{幸葍}努か 提交于 2019-12-02 05:16:52

swift 2+ solution:

do {
  try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
  try AVAudioSession.sharedInstance().setActive(true)
} catch _ {
  return print("error")
}

You use wrong category, for AVAudioSessionCategoryAmbient it's normal behavior "Your audio is silenced by screen locking and by the Silent switch". Use AVAudioSessionCategoryPlayback instead.

first of all you should add background mode to your plist like this:

Then you should use AVAudioSessionCategoryPlayback session. Like this:

AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil)

AVAudioSessionCategoryAmbient does not work in background.

Open your app info.plist as Source code (to edit in text mode) and add the following just after dict:

<key>UIBackgroundModes</key>
<array>
    <string>audio</string>
</array>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!