如何使用SwiftUI在VStack中显示我的AVPlayer

时间:2019-06-30 06:44:08

标签: avplayer swiftui

我创建了一个简单的AVPlayer。 (如果我没有正确创建它,请帮助我修复它...?)我想用swift ui在我的VStack中显示它,但是我有点卡住了...

如果库中至少有AVPlayer View组件,那会更容易,但是我没有在库中找到它...?

这是我在ContentView.swift中的代码:

//
//  ContentView.swift
//  test
//
//  Created by Francis Dolbec on 2019-06-26.
//  Copyright © 2019 Francis Dolbec. All rights reserved.
//

import SwiftUI
import AVKit
import AVFoundation

// MARK: variables
var hauteurMenuBar = NSApplication.shared.mainMenu?.menuBarHeight
var urlVideo = URL(string: "/Users/francisdolbec/Movies/Séries Télé/Rick et Morty/Rick.and.Morty.S01E01.VFQ.HDTV.1080p.x264-Kamek.mp4")
let player = AVPlayer(url: urlVideo!)


struct ContentView : View {
    var body: some View {

        VStack {
            Text("Hello World")
                .frame(maxWidth: .infinity, maxHeight: .infinity)
            Text("PATATE!")
            //player.play()
            }

        .frame(minWidth: 1024, idealWidth: 1440, maxWidth: .infinity, minHeight: (640-hauteurMenuBar!), idealHeight: (900-hauteurMenuBar!), maxHeight: .infinity)

    }
}


#if DEBUG
struct ContentView_Previews : PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
#endif

顺便说一句,如果有一个教程展示了如何使用swift ui制作视频播放器,我将非常感谢!

编辑 我忘了说我正在开发 macOS 应用。

1 个答案:

答案 0 :(得分:2)

当然,这是Chris Mash on Medium撰写的教程。

基本上,您将AVPlayerLayer嵌入到符合UIViewRepresentable的结构中,这是您要与SwiftUI一起使用的任何UIView组件所要做的。

struct PlayerView: UIViewRepresentable {
  func updateUIView(_ uiView: UIView, context: UIViewRepresentableContext<PlayerView>) {
  }

  func makeUIView(context: Context) -> UIView {
    return PlayerUIView(frame: .zero)
  }
}

实现的“实质”是在PlayerUIView类中完成的:

class PlayerUIView: UIView {
  private let playerLayer = AVPlayerLayer()

  override init(frame: CGRect) {
    super.init(frame: frame)

    let url = URL(string: “https://bitdash-a.akamaihd.net/content/sintel/hls/playlist.m3u8")!
    let player = AVPlayer(url: url)
    player.play()

    playerLayer.player = player
    layer.addSublayer(playerLayer)
  }

  required init?(coder: NSCoder) {
     fatalError(“init(coder:) has not been implemented”)
  }

  override func layoutSubviews() {
    super.layoutSubviews()
    playerLayer.frame = bounds
  }
}

然后像这样使用它:

var body: some View {
  PlayerView()
}