Home > Back-end >  SwiftUI: Play button in the native VideoPlayer
SwiftUI: Play button in the native VideoPlayer

Time:12-17

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://vod-progressive.akamaized.net/exp=1639690218~acl=/vimeo-prod-skyfire-std-us/01/4047/11/295238750/1123020046.mp4~hmac=f65c0f2ca7cd1a8cee5efd11a00b305682cbfc03e5999c1b948e9cc47788b6b9/vimeo-prod-skyfire-std-us/01/4047/11/295238750/1123020046.mp4?filename=What Star Wars Can Teach Us About Swift.mp4")!))
        .frame(height: 228)
      Spacer()
      Button {
        print("play video from this button...")
      } label: {
        Text("Play")
          .font(.system(size: 26))
      }
    }
    .padding(.vertical, 16)
  }
}

CodePudding user response:

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=/vimeo-prod-skyfire-std-us/01/4047/11/295238750/1123020046.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

  • Related