An Interest In:
Web News this Week
- March 21, 2024
- March 20, 2024
- March 19, 2024
- March 18, 2024
- March 17, 2024
- March 16, 2024
- March 15, 2024
October 4, 2021 07:27 pm GMT
Original Link: https://dev.to/toni777772/how-to-play-a-video-with-videoplayer-in-swiftui-o0c
How to play a video with VideoPlayer in SwiftUI
VideoPlayer - is a view that displays content from a player and a native user interface to control playback.
Available iOS 14.0+, macOS 11.0+, Mac Catalyst 14.0+, tvOS 14.0+, watchOS 7.0+, Xcode 12.0+.
How to use the VideoPlayer view? Go to the code below:
import AVKit // 1import SwiftUIstruct ContentView: View { // 2 let videoUrl = URL(fileURLWithPath: Bundle.main.path(forResource: "PexelsSea", ofType: "mp4")!) var body: some View { VideoPlayer(player: AVPlayer(url: videoUrl)) // 3 .frame(height: 320) }}
- The first step is to import the
AVKit
framework. - The second step is create video
URL
. TheURL
can be created for local video or remote. In our code case, a URL was created for local video from the bundle. - Final step is to pass
AVPlayer
, as the first parameter toVideoPlayer
view.
The
VideoPlayer
view has playback controls.
Result:
Video Overlay (Watermark)
A VideoPlayer
has another init
function with two parameters:
init(player: AVPlayer?, @ViewBuilder videoOverlay: () -> VideoOverlay)
- First parameter is
AVPlayer
. - Second parameter is
videoOverlay
closure. The closure returns aVideoOverlay
view to present over the players video content.second parameter. The important thing is this overlay view is fully interactive, but is placed below the system-provided playback controls, and only receives unhandled events.
Let's go to the code. As an example, will add a simple text in the lower right corner.
import AVKit import SwiftUIstruct ContentView: View { let videoUrl = URL(fileURLWithPath: Bundle.main.path(forResource: "PexelsSea", ofType: "mp4")!) var body: some View { VideoPlayer(player: AVPlayer(url: url), videoOverlay: { VStack { Spacer() HStack { Spacer() Text("Code sample by ToniDevBlog") .foregroundColor(.white) } }.padding() }).frame(height: 320) }}
Result:
Full source code available on GitHub
Article originally published at ToniDevBlog
Thanks for reading! See you soon.
Original Link: https://dev.to/toni777772/how-to-play-a-video-with-videoplayer-in-swiftui-o0c
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To