【问题标题】:Control audio outside app in iOS在 iOS 中控制应用程序外部的音频
【发布时间】:2017-11-01 16:07:34
【问题描述】:

我正在尝试从应用外部控制我的音频播放器, 我开始了一个 av 音频会话,但它没有在后台播放(在 swift 3 上运行良好),

        do{


        myPlayer =  AVPlayer(url: url!)

        let audioSession = AVAudioSession.sharedInstance()
        do {
            try audioSession.setCategory(AVAudioSessionCategoryPlayback
            )
            do {
                try audioSession.setActive(true)

            }

        }
        catch {
            print(error)
        }
    }

我的主要目标是像这样控制播放和暂停:

【问题讨论】:

标签: ios swift audio avfoundation


【解决方案1】:

因此,您正在构建一个使用 AVPlayer 在后台播放音频的应用。您应该使用MPNowPlayingInfoCenter 在锁定屏幕和控制中心显示歌曲的元数据,并使用MPRemoteCommandCenter 在锁定屏幕和控制中心控制上一个/下一个/播放/暂停操作。

  • 启用音频、AirPlay 和图片输入的背景模式 图片在您的Target > Capabilities中。
  • 如果您从网络流式传输音频,请也为 Background Fetch 启用背景模式。

  • 导入AVKitMediaPlayer 依赖项。

使用AVPlayerItem 设置您的AVPlayer

guard let url = URL(string: "http://your.website.com/playlist.m3u8") else {
    return
}
player = AVPlayer(url: url)

设置您的AVAudioSession:

private func setupAVAudioSession() {
    do {
        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
        try AVAudioSession.sharedInstance().setActive(true)
        debugPrint("AVAudioSession is Active and Category Playback is set")
        UIApplication.shared.beginReceivingRemoteControlEvents()
        setupCommandCenter()
    } catch {
        debugPrint("Error: \(error)")
    }
}

设置InfoCenterRemoteCommandCenter

private func setupCommandCenter() {
    MPNowPlayingInfoCenter.default().nowPlayingInfo = [MPMediaItemPropertyTitle: "Your App Name"]

    let commandCenter = MPRemoteCommandCenter.shared()
    commandCenter.playCommand.isEnabled = true
    commandCenter.pauseCommand.isEnabled = true
    commandCenter.playCommand.addTarget { [weak self] (event) -> MPRemoteCommandHandlerStatus in
        self?.player.play()
        return .success
    }
    commandCenter.pauseCommand.addTarget { [weak self] (event) -> MPRemoteCommandHandlerStatus in
        self?.player.pause()
        return .success
    }
}

您可以将setupAVAudioSession() 方法放在您的viewDidLoad() 方法中,或者放在您需要的任何其他地方。

如果您需要在MPNowPlayingInfoCenter 中添加更多信息,请查看所有可用属性的列表:General Media Item Property Keys | Apple Developer Documentation

【讨论】:

  • 我不知道为什么这个答案没有更多的赞成票。非常有用的信息。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-18
相关资源
最近更新 更多