Are you looking to add videos to your SwiftUI app? Look no further, because we’ve got you covered! In this article, we’ll go over how to load and play videos in pure SwiftUI.
First, let’s define the components we’ll be using. To load and play videos, we’ll be using the VideoPlayer and AVPlayercomponents from the AVFoundation framework. The VideoPlayer component is a SwiftUI view that wraps an AVPlayerobject, which handles the playback of the video.
Now, let’s dive into the code. To load and play a video, we first need to create an AVPlayer object and wrap it in a VideoPlayer view. Here's an example:
struct VideoPlayerView: View {
var body: some View {
VideoPlayer(player: AVPlayer(url: URL(string: "https://example.com/video.mp4")!))
.onAppear {
// Play the video automatically when it appears
AVPlayer.shared().play()
}
.onDisappear {
// Pause the video when it disappears
AVPlayer.shared().pause()
}
}
}
In this example, we define a VideoPlayerView that displays a video from a URL. We use the VideoPlayer view to display the video, and the onAppear and onDisappear modifiers to start and stop playback of the video.
But what if you want to control playback of the video yourself? Fear not, because we can do that too! Here’s an example of how to add playback controls to the VideoPlayer view:
struct VideoPlayerView: View {
@State var isPlaying: Bool = false
var body: some View {
VStack {
VideoPlayer(player: AVPlayer(url: URL(string: "https://example.com/video.mp4")!))
.onAppear {
// Play the video automatically when it appears
AVPlayer.shared().play()
}
.onDisappear {
// Pause the video when it disappears
AVPlayer.shared().pause()
}
HStack {
Button(action: {
// Rewind the video by 10 seconds
AVPlayer.shared().seek(to: CMTime(seconds: max(0, CMTimeGetSeconds(AVPlayer.shared().currentTime()) - 10), preferredTimescale: 1))
}) {
Image(systemName: "gobackward.10")
.foregroundColor(.black)
}
Button(action: {
// Toggle play/pause of the video
isPlaying.toggle()
if isPlaying {
AVPlayer.shared().play()
} else {
AVPlayer.shared().pause()
}
}) {
Image(systemName: isPlaying ? "pause.fill" : "play.fill")
.foregroundColor(.black)
}
Button(action: {
// Fast forward the video by 10 seconds
AVPlayer.shared().seek(to: CMTime(seconds: min(CMTimeGetSeconds(AVPlayer.shared().currentTime()) + 10, CMTimeGetSeconds(AVPlayer.shared().currentItem!.duration)), preferredTimescale: 1))
}) {
Image(systemName: "goforward.10")
.foregroundColor(.black)
}
}
}
}
}
In this example, we define a VideoPlayerView that displays a video and playback controls. We use the @State property wrapper to toggle playback of the video, and the Button view to create the playback controls.
Give Support or Tip👋🏿
Give a Tip with CashApp: https://cash.app/$DiAlcatic
Comments