如何在CarPlay上播放视频?

时间:2019-07-08 16:18:00

标签: ios swift avfoundation avplayer carplay

我有一个视频链接,在iOS中,我可以使用AVPlayerViewController / AVPlayer内的AVFoundation / AVKit框架将其打开。

但是如何在CarPlay中打开它?

CarPlay文档中的文字:

  

您不能直接使用媒体播放器播放视频媒体项目   框架。要播放包含MPMediaItem对象的视频,请使用   AVFoundation的AVPlayer对象。系统播放器还提供了一个   使用系统应用程序播放视频项目的方法。

extension AppDelegate: CPListTemplateDelegate {
    func listTemplate(_ listTemplate: CPListTemplate, didSelect item: CPListItem, completionHandler: @escaping () -> Void) {
        if let url = item.userInfo as? String {
            self.playVideo(url)
        }
    }
}

1 个答案:

答案 0 :(得分:2)

我将分享在汽车游戏中播放示例视频的步骤

在Appdeligate.h中添加以下头文件

import CarPlay
import AVKit

然后添加CPApplicationDelegate

添加这些忠实的方法

 // MARK: - CPApplicationDelegate methods
func application(_ application: UIApplication, didConnectCarInterfaceController interfaceController: CPInterfaceController, to window: CPWindow) {
    print("[CARPLAY] CONNECTED TO CARPLAY!")

    // Keep references to the CPInterfaceController (handles your templates) and the CPMapContentWindow (to draw/load your own ViewController's with a navigation map onto)
    self.interfaceController = interfaceController
    self.carWindow = window
    guard let path = Bundle.main.path(forResource: "video", ofType: "mp4") else
                        {
                            return
                        }
                        let videoURL = NSURL(fileURLWithPath: path)
                        let player = AVPlayer(url: videoURL as URL)
                        let playerController = AVPlayerViewController()
                        playerController.player = player
                        player.play()

            window.rootViewController = playerController
}

func application(_ application: UIApplication, didDisconnectCarInterfaceController interfaceController: CPInterfaceController, from window: CPWindow) {
    print("[CARPLAY] DISCONNECTED FROM CARPLAY!")
}

还可以执行以下步骤来添加汽车游戏权利