Playing Videos in SwiftUI & AVKit 

DevTechie Inc
Jun 11, 2022

Photo by Denise Jans on Unsplash

SwiftUI VideoPlayer view let’s us play video files located either locally within the project or file located at a remote location available via url.

VideoPlayer view is part of AVKit framework and importing the framework is all you need to get started with the video player view 😃

VideoPlayer view takes AVPlayer as parameter where you have an opportunity to set video url either from your app bundle via Bundle.main.url(forResource:withExtension:) or you can create remote URL object(which is what we will do).

Let’s create a view to play video from a url. We will use one of the most famous sample video clip called “Big Buck Bunny” .

import SwiftUI
import AVKitstruct VideoPlayerExample: View {
    var body: some View {
        VStack {
            Text("DevTechie")
                .font(.largeTitle)
            Text("Presents")
                .font(.caption)
            Text("Video player demo with Big Buck Bunny")
            VideoPlayer(player: AVPlayer(url: URL(string: "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4")!))
        }
    }
}
Here is how our view will look like:

VideoPlayer view takes all the available space provided by the parent view just like Color view. Along with default play pause button, it comes with AirPlay and Volume control as well.

Video Overlay
VideoPlayer view has another parameter of VideoOverlay view type. This parameter will let you add an overlay to your video player. One use case could be to add your brand logo or watermark on the video as shown below. This will add DevTechie watermark at the bottom of VideoPlayer view.

struct VideoPlayerExample: View {
    var body: some View {
        VStack {
            Text("DevTechie")
                .font(.largeTitle)
            Text("Presents")
                .font(.caption)
            Text("Video player demo with Big Buck Bunny")
            VideoPlayer(player: AVPlayer(url: URL(string: "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4")!)) { 
                VStack {
                    Spacer()
                    Text("DevTechie")
                        .font(.largeTitle)
                        .opacity(0.2)
                }            
            }
        }
    }
}

With that we have reached the end of this article. Thank you once again for reading. Don’t forget to subscribe to our weekly newsletter at https://www.devtechie.com