Skip to main content

How to play movies with VideoPlayer

About 2 minSwiftSwiftUIArticle(s)bloghackingwithswift.comcrashcourseswiftswiftuixcodeappstore

How to play movies with VideoPlayer 관련

SwiftUI by Example

Back to Home

How to play movies with VideoPlayer | SwiftUI by Example

How to play movies with VideoPlayer

Updated for Xcode 15

SwiftUI's VideoPlayer view lets us playback movies from any URL, local or remote. It comes from the AVKit framework, so you should make sure and add import AVKit before trying it out.

As an example, if you had video.mp4 in your app bundle and wanted to play it back, you'd use this:

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

Download this as an Xcode projectopen in new window

A video showing Niagara Falls, playing inside an iPhone.
A video showing Niagara Falls, playing inside an iPhone.

Reminder

You need to add import AVKit to your Swift file to use this.

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

VideoPlayer(player: AVPlayer(url:  URL(string: "https://bit.ly/swswift")!))
    .frame(height: 400)

Download this as an Xcode projectopen in new window

A video with a play button overlaid, inside an iPhone.
A video with a play button overlaid, inside an iPhone.

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

For example, this places the text “Watermark” at the very top of the video area:

VideoPlayer(player: AVPlayer(url:  URL(string: "https://bit.ly/swswift")!)) {
    VStack {
        Text("Watermark")
            .foregroundStyle(.black)
            .background(.white.opacity(0.7))
        Spacer()
    }
    .frame(width: 400, height: 300)
}

Download this as an Xcode projectopen in new window

A video with a play button overlaid, along with the word Watermark place at the top.

Similar solutions…
Article(s) > How to add search tokens to a search field

How to add search tokens to a search field
How to let users import videos using PhotosPicker | SwiftUI by Example

How to let users import videos using PhotosPicker
SwiftUI tips and tricks | SwiftUI by Example

SwiftUI tips and tricks
How to add haptic effects using sensory feedback | SwiftUI by Example

How to add haptic effects using sensory feedback
How to animate SF Symbols | SwiftUI by Example

How to animate SF Symbols

이찬희 (MarkiiimarK)
Never Stop Learning.