简体   繁体   中英

How to properly make background audio playback on iOS work?

I'm trying to build an Radio Streaming app. I have created a Singleton class for may RadioPlayer as described bellow and I have turned on Background Modes > Audio, AirPlay and Picture in Picture.

However, when my App goes into background mode, the audio stops playing. What am I missing here?

Appreciate any help! Thanks!

import Foundation
import AVFoundation

class RadioPlayer {

  static let sharedInstance = RadioPlayer()

  var player = AVPlayer(playerItem: RadioPlayer.radioPlayerItem())
  var isPlaying = false

  class func radioPlayerItem() -> AVPlayerItem {
    return AVPlayerItem(URL: urlRadio())
  }

  class func urlRadio() -> NSURL {
    let roRadio = Repository.realm.objects(RORadio)
    let url: NSURL = NSURL(string: roRadio[0].streaming)!
    return url
  }

  func toggle() {
    if isPlaying == true {
      pause()
    } else {
      play()
    }
  }

  func play() {
    player.play()
    isPlaying = true
  }

  func pause() {
    player.pause()
    isPlaying = false
  }

  func currentlyPlaying() -> Bool {
    return isPlaying
  }
}

The application should be allowed to continue running while in the background. Open your Info.plist file and add the key of UIBackgroundModes. There will be only one string "audio" for your aim.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM