How to Play Videos with AVPlayer in SwiftUI

Add a video or an audio player to your SwiftUI application by using AVPlayer and AVKit

If you want to integrate a video or an audio player in your application, AVPlayer is the way to go. 

It's easy and fast to implement, and provides all the necessary tools for you to manage the video.

Create the player 

Import AVKit at the top of your file.

import AVKit

..

Create a player with a @State variable. The value will be an AVPlayer() object.

@State var player = AVPlayer()

..

Create another variable for the video link, and set it to any video file link.

var videoUrl: String = "https://www.w3schools.com/html/mov_bbb.mp4"

..

Please note that YouTube links are not supported with AVPlayer as the links aren't direct links to the video file, but rather links to the page or player itself. AVPlayer requires a link to the actual mp4 file, and not a link to another video player or to a page.

There are tools that can help you get the video file link, but it might be better to use an iFrame player in a WebView when dealing with YouTube links.

In your body, add the VideoPlayer view:

var body: some View {
		VideoPlayer(player: player)
}

..

Add an .onAppear modifier which will add the videoUrl to your VideoPlayer. Remember to force-unwrap your videoUrl with ! at the end to silence Xcode's optional URL error.

var body: some View {
		VideoPlayer(player: player)
				.onAppear() {
						player = AVPlayer(url: URL(string: videoUrl)!)
				}
}

..

And now you have a player in your SwiftUI application! Learn how to control the video by reading the Controls with AVPlayer section.

Comments