VideoPlayer
A view that displays content from a player and a native user interface to control playback.
Declaration
@MainActor @preconcurrency struct VideoPlayer<VideoOverlay> where VideoOverlay : ViewOverview
import SwiftUI
import AVKit
struct ContentView: View {
/// An optional player the view creates in a task modifier.
///
/// Creating the player instance indirectly helps to avoid
/// performance issues and other side effects.
@State private var player: AVPlayer?
@State private var isPlaying = false
var body: some View {
VStack {
if let player {
VideoPlayer(player: player)
.frame(width: 320, height: 180, alignment: .center)
Button {
isPlaying ? player.pause() : player.play()
isPlaying.toggle()
player.seek(to: .zero)
} label: {
Image(systemName: isPlaying ? "stop" : "play")
.padding()
}
}
}
.task {
// Use the task modifier to defer creating the player to ensure
// SwiftUI creates it only once when it first presents the view.
let url = // URL to local or remote media.
player = AVPlayer(url: url)
}
}
}