How to play movies with VideoPlayer

By | September 29, 2024

Playing movie or videos from any source is important when it comes to application development. Apple provides some default frameworks to handle it. SwiftUI’s VideoPlayer view lets us playback movies from any URL, local or remote. It comes from the AVKit framework, this can be added to the framework by importing AVKit.

The below example shows how to play a sample video that is locally available in our app bundle.

   VideoPlayer(player: AVPlayer(url:  Bundle.main.url(forResource: "anime", withExtension: "mp4")!))
                .frame(height: 500)

If you want to play a remote video, use its remote URL instead:

var body: some View {
        VStack {
            VideoPlayer(player: AVPlayer(url:  URL(string: "https://yoursite.com/anime.mp4")!))
                .frame(height: 500)
        }
    }

If you want, you can provide a second parameter to the VideoPlayer initializer that adds content to be drawn over the video. This can be used to draw system video controls, but can respond to any events that aren’t caught by those controls.

Also we can place the text “Watermark” at the very top of the video area.

VideoPlayer(player: AVPlayer(url:  URL(string: "https://yoursite.com/video.mp4")!)) {
    VStack {
        Text("Codersheaven")
            .foregroundStyle(.black)
            .background(.white.opacity(0.7))
        Spacer()
    }
    .frame(width: 400, height: 300)
}

Leave a Reply

Your email address will not be published. Required fields are marked *