【问题标题】:MPRemoteCommandCenter - Remote controls on lock screen does not show upMPRemoteCommandCenter - 锁定屏幕上的遥控器不显示
【发布时间】:2021-11-14 18:12:42
【问题描述】:

我在 View 控制器中实现了两个函数(setupRemoteTransportControls() 和 setupNowPlaying()),并向 AppDelegate 添加了一个函数,但我仍然无法在锁定屏幕上看到我的应用程序的背景音频控件以及音频中断功能不工作。这是来自 url 的实时流,您可以在代码中看到。在常规设置中,我添加了后台播放:

我想做的是在远程命令中心艺术家、标题和专辑艺术标签和 UIImage 上打印(标签 UIImage 取自我的站 API),但我只是显示命令中心时卡住了。这是我的代码:

import UIKit
import AVKit
import MediaPlayer
class ViewController: UIViewController, AVAudioPlayerDelegate {

@IBAction func buttonPressed(_ sender: UIButton){
              if isPlaying {
                   player.pause()
                   sender.setImage(playImage, for: .normal)
              } else {
                   let url = "https://myradio.com/radio.mp3"
                   do {
                        try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: [.mixWithOthers, .allowAirPlay])
                        try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback, options: [])
                        print("Playback OK")
                        try AVAudioSession.sharedInstance().setActive(true)
                        print("Session is Active")
                   } catch {
                        print(error)
                   }
                   
                   player = AVPlayer(url: URL(string: url)!)
                   player.volume = 1.0
                   player.rate = 1.0
                   player.play()
                sender.setImage(pauseImage, for: .normal)
              }
              
              isPlaying.toggle()
         }


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        overrideUserInterfaceStyle = .light
        setupRemoteTransportControls()
        requestNowPlaying()
        setupNowPlaying()
    }

// Here is the API data downloading part, so i skipped it 


    //Command Center audio controls
    
    func setupRemoteTransportControls() {
        // Get the shared MPRemoteCommandCenter
        let commandCenter = MPRemoteCommandCenter.shared()
        // Add handler for Play Command
        commandCenter.playCommand.addTarget { [unowned self] event in
            if self.player.rate == 1.0 {
                self.player.play()
                return .success
            }
            return .commandFailed
        }

        // Add handler for Pause Command
        commandCenter.pauseCommand.addTarget { [unowned self] event in
            if self.player.rate == 1.0 {
                self.player.pause()
                return .success
            }
            return .commandFailed
        }
    }

    func setupNowPlaying() {
        // Define Now Playing Info
        var nowPlayingInfo = [String : Any]()
        nowPlayingInfo[MPMediaItemPropertyTitle] = "Test"

        if let image = UIImage(named: "Default_albumart") {
            nowPlayingInfo[MPMediaItemPropertyArtwork] = MPMediaItemArtwork(boundsSize: image.size) { size in
                return image
            }
        }
        nowPlayingInfo[MPNowPlayingInfoPropertyIsLiveStream] = true
        

        // Set the metadata
        MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo
    }


    func updateNowPlaying(isPause: Bool) {
        // Define Now Playing Info
        let nowPlayingInfo = MPNowPlayingInfoCenter.default().nowPlayingInfo!

        //nowPlayingInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = player.currentTime
        //nowPlayingInfo[MPNowPlayingInfoPropertyPlaybackRate] = isPause ? 0 : 1

        // Set the metadata
        MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo
    }
    

    
    
//audio interruption
    @objc func handleInterruption(notification: Notification) {
        guard let userInfo = notification.userInfo,
                let typeValue = userInfo[AVAudioSessionInterruptionTypeKey] as? UInt,
                let type = AVAudioSession.InterruptionType(rawValue: typeValue) else {
                    return
            }

            // Switch over the interruption type.
            switch type {

            case .began:
                print("Interruption began")
                

            case .ended:
               // An interruption ended. Resume playback, if appropriate.

                guard let optionsValue = userInfo[AVAudioSessionInterruptionOptionKey] as? UInt else { return }
                let options = AVAudioSession.InterruptionOptions(rawValue: optionsValue)
                if options.contains(.shouldResume) {
                    player.play()
                } else {
                    // An interruption ended. Don't resume playback.
                }

            default: ()
            }
        }
    
            
    
}

这是我在 My AppDelegate.swift 中添加的内容:

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        application.beginReceivingRemoteControlEvents()
     //    Override point for customization after application launch.
       return true
    }

【问题讨论】:

    标签: ios swift avfoundation avaudiosession mpremotecommandcenter


    【解决方案1】:

    从您的类别选项中删除 .mixWithOthers。 我认为原因是只有主要的 iOS 音频应用程序才能控制远程屏幕。 .mixWithOthers 用于辅助音频应用。

    【讨论】:

    • @Rhytmic Fistman - 你知道为什么 ```handleInterruption`` 函数不起作用吗?我想在通话或使用 siri 后继续播放音乐。
    • 我也不知道为什么我的专辑封面根本不显示。
    【解决方案2】:

    使用此代码将自己标识为 .longForm 音频内容提供者:

    try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, mode: AVAudioSessionModeDefault, routeSharingPolicy: .longForm)
    

    有关 AirPlay2 的完整实施,请查看此 Apple WWDC 演示文稿:https://developer.apple.com/videos/play/wwdc2017/509/

    【讨论】:

    • @MrSwiftOak 是否有必要添加此代码?我是说它有什么变化?也感谢您的链接。
    • 好的,我已经检查过了。您的代码在 iOS 13 中已弃用。现在是 .longFormAudio 有效的是:try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback, mode: AVAudioSession.Mode.default, policy: AVAudioSession.RouteSharingPolicy.longFormAudio)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多