Daryl Wong
Daryl Wong

Reputation: 2443

SwiftUI: Play button in the native VideoPlayer

SwiftUI comes with a native video player. Can the play be triggered by a button like below instead of from the integrated control.

import AVKit

struct ContentView: View {
  
  var body: some View {
    VStack {
      VideoPlayer(player: AVPlayer(url:  URL(string: "https://firebasestorage.googleapis.com/v0/b/celebenglish-185ab.appspot.com/o/videos%2Fdec%2Fc6klrs.mp4?alt=media&token=288c4e00-b23f-4d7f-84d3-00ab3bfb68a4")!))
        .frame(height: 228)
      Spacer()
      Button {
        print("play video from this button...")
      } label: {
        Text("Play")
          .font(.system(size: 26))
      }
    }
    .padding(.vertical, 16)
  }
}

Upvotes: 1

Views: 1956

Answers (1)

Asperi
Asperi

Reputation: 257643

We can do that with player directly, like

struct ContentView: View {
    private let player = AVPlayer(url:  URL(string: "https://vod-progressive.akamaized.net/exp=1639690218~acl=%2Fvimeo-prod-skyfire-std-us%2F01%2F4047%2F11%2F295238750%2F1123020046.mp4~hmac=f65c0f2ca7cd1a8cee5efd11a00b305682cbfc03e5999c1b948e9cc47788b6b9/vimeo-prod-skyfire-std-us/01/4047/11/295238750/1123020046.mp4?filename=What+Star+Wars+Can+Teach+Us+About+Swift.mp4")!)

  var body: some View {
    VStack {
      VideoPlayer(player: player)
        .frame(height: 228)
      Spacer()
      Button {
        player.play()     // << here !!
      } label: {
        Text("Play")
          .font(.system(size: 26))
      }
    }
    .padding(.vertical, 16)
  }
}

Tested with Xcode 13 / iOS 15

Upvotes: 2

Related Questions