Created
September 18, 2024 18:07
-
-
Save wotjd/8c63bb07dcfc4242fa88fa7617fde0d9 to your computer and use it in GitHub Desktop.
an implementation of UIKit bridged LoopPlayerView
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
import AVKit | |
// NOTE: be careful when use as it has state problem. | |
struct LoopPlayerView: View { | |
let player: AVQueuePlayer | |
let playerItem: AVPlayerItem | |
let configuration: PlayerView.Configuration | |
private let looper: AVPlayerLooper | |
init( | |
player: AVQueuePlayer = AVQueuePlayer(), | |
playerItem: AVPlayerItem, | |
configuration: @escaping PlayerView.Configuration = { | |
$0.showsPlaybackControls = false | |
$0.videoGravity = .resizeAspectFill | |
} | |
) { | |
self.player = player | |
self.playerItem = playerItem | |
self.configuration = configuration | |
looper = AVPlayerLooper(player: player, templateItem: playerItem) | |
} | |
var body: some View { | |
PlayerView(player: player, configuration: configuration) | |
.onAppear { player.play() } | |
.onDisappear { player.pause() } | |
} | |
} | |
struct PlayerView: UIViewControllerRepresentable { | |
typealias Configuration = (AVPlayerViewController) -> Void | |
let player: AVPlayer | |
let configuration: Configuration | |
init( | |
player: AVPlayer, | |
configuration: @escaping Configuration = { _ in } | |
) { | |
self.player = player | |
self.configuration = configuration | |
} | |
func makeUIViewController(context: Context) -> some UIViewController { | |
{ | |
$0.player = player | |
configuration($0) | |
return $0 | |
}(AVPlayerViewController()) | |
} | |
func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) { | |
} | |
} | |
#Preview { | |
LoopPlayerView( | |
playerItem: AVPlayerItem(url: Bundle.main.url(forResource: "the_cat", withExtension: "mp4")!) | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment