简体   繁体   English

如何在iOS上正常播放背景音频?

[英]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. 我如下所述为May RadioPlayer创建了Singleton类,并打开了“背景模式”>“音频”,“ AirPlay”和“画中画”。

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. 打开您的Info.plist文件,然后添加UIBackgroundModes的键。 There will be only one string "audio" for your aim. 您的目标只有一个字符串“音频”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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