Create a Video Player in SwiftUI
Written by Team Kodeco
Playing videos is an essential component of a modern user interface. SwiftUI makes it easy to play videos by providing the VideoPlayer view. In this cookbook entry, you will learn how to create a basic video player in SwiftUI.
Note: If you want to try out the examples, you can download an archive of all the assets used in this section here.
To start, you need to import the AVKit framework in your project. This framework provides the necessary classes to play videos in SwiftUI. Next, add the following code to create and display a VideoPlayer
view:
import AVKit
struct VideoPlayerView: View {
// Create a URL for the video file in your app bundle
let videoURL: URL? = Bundle.main.url(forResource: "BookTrailer", withExtension: "m4v")
var body: some View {
VStack {
if let url = videoURL {
VideoPlayer(player: AVPlayer(url: url))
} else {
Text("Video not found")
}
}
}
}
struct ContentView: View {
var body: some View {
VideoPlayerView()
}
}
Your preview should look like this:
Let’s break down the code:
-
struct VideoPlayerView: View
declares a new SwiftUIView
namedVideoPlayerView
. -
let videoURL: URL? = Bundle.main.url(forResource: "BookTrailer", withExtension: "m4v")
defines a URL for the video file in the app’s bundle. It attempts to locate a file named “BookTrailer.m4v” in the main app bundle. -
var body: some View
declares the main content ofVideoPlayerView
. -
if let url = videoURL { VideoPlayer(player: AVPlayer(url: url)) } else { Text("Video not found") }
checks if thevideoURL
has been set. If the video file was found, aVideoPlayer
view is created that plays the video at the given URL. If not, aText
view is created that displays the message “Video not found”. -
struct ContentView: View { var body: some View { VideoPlayerView() } }
declares a new SwiftUIView
namedContentView
which displays theVideoPlayerView
when it’s shown.
Creating a video player in SwiftUI is as simple as creating a VideoPlayer view and adding an AVPlayer object with the URL of the video to play. You can further customize the video player by modifying the properties of the AVPlayer object.