Swift: Keep playing sounds when the device is locked

后端 未结 4 1000
眼角桃花
眼角桃花 2021-01-15 04:50

I\'m using the following code to play a sound off a URL from the internet:

var audioPlayer = AVPlayer()

...

let audioSessio         


        
相关标签:
4条回答
  • 2021-01-15 05:19

    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>
    
    0 讨论(0)
  • 2021-01-15 05:21

    swift 2+ solution:

    do {
      try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
      try AVAudioSession.sharedInstance().setActive(true)
    } catch _ {
      return print("error")
    }
    
    0 讨论(0)
  • 2021-01-15 05:30

    first of all you should add background mode to your plist like this:enter image description here

    Then you should use AVAudioSessionCategoryPlayback session. Like this:

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

    AVAudioSessionCategoryAmbient does not work in background.

    0 讨论(0)
  • 2021-01-15 05:35

    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.

    0 讨论(0)
提交回复
热议问题