custom player

This commit is contained in:
cranci1 2024-12-23 16:13:37 +01:00
parent 71d243dba5
commit ff6b01c429
6 changed files with 145 additions and 72 deletions

View file

@ -12,7 +12,7 @@ struct CustomVideoPlayer: UIViewControllerRepresentable {
let player: AVPlayer
func makeUIViewController(context: Context) -> AVPlayerViewController {
let controller = CustomAVPlayerViewController()
let controller = NormalPlayer()
controller.player = player
controller.showsPlaybackControls = false
player.play()
@ -24,16 +24,6 @@ struct CustomVideoPlayer: UIViewControllerRepresentable {
}
}
class CustomAVPlayerViewController: AVPlayerViewController {
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
if UserDefaults.standard.bool(forKey: "alwaysLandscape") {
return .landscape
} else {
return .all
}
}
}
struct CustomMediaPlayer: View {
@State private var player: AVPlayer
@State private var isPlaying = true
@ -41,13 +31,23 @@ struct CustomMediaPlayer: View {
@State private var duration: Double = 0.0
@State private var showControls = false
@State private var inactivityTimer: Timer?
@State private var timeObserverToken: Any?
@Environment(\.presentationMode) var presentationMode
init(urlString: String) {
let fullUrl: String
let title: String
let episodeNumber: Int
let onWatchNext: () -> Void
init(urlString: String, fullUrl: String, title: String, episodeNumber: Int, onWatchNext: @escaping () -> Void) {
guard let url = URL(string: urlString) else {
fatalError("Invalid URL string")
}
_player = State(initialValue: AVPlayer(url: url))
self.fullUrl = fullUrl
self.title = title
self.episodeNumber = episodeNumber
self.onWatchNext = onWatchNext
}
var body: some View {
@ -63,6 +63,7 @@ struct CustomMediaPlayer: View {
}
}
startUpdatingCurrentTime()
addPeriodicTimeObserver(fullURL: fullUrl)
}
.edgesIgnoringSafeArea(.all)
.overlay(
@ -118,11 +119,30 @@ struct CustomMediaPlayer: View {
VStack {
Spacer()
if showControls {
VStack {
VStack {
Spacer()
HStack {
Spacer()
HStack {
Spacer()
if duration - currentTime <= duration * 0.06 {
Button(action: {
player.pause()
presentationMode.wrappedValue.dismiss()
onWatchNext()
}) {
HStack {
Image(systemName: "forward.fill")
.foregroundColor(Color.black)
Text("Watch Next")
.font(.headline)
.foregroundColor(Color.black)
}
.padding()
.background(Color.white.opacity(0.8))
.cornerRadius(32)
}
.padding(.trailing, 10)
}
if showControls {
Menu {
Menu("Playback Speed") {
Button(action: {
@ -196,8 +216,10 @@ struct CustomMediaPlayer: View {
.font(.system(size: 15))
}
}
.padding(.trailing, 10)
}
.padding(.trailing, 10)
if showControls {
MusicProgressSlider(
value: $currentTime,
inRange: 0...duration,
@ -211,8 +233,8 @@ struct CustomMediaPlayer: View {
}
}
)
.frame(height: 45)
.padding(.bottom, 10)
.frame(height: 45)
.padding(.bottom, 10)
}
}
}
@ -222,6 +244,10 @@ struct CustomMediaPlayer: View {
.onDisappear {
player.pause()
inactivityTimer?.invalidate()
if let timeObserverToken = timeObserverToken {
player.removeTimeObserver(timeObserverToken)
self.timeObserverToken = nil
}
}
}
}
@ -235,6 +261,7 @@ struct CustomMediaPlayer: View {
.foregroundColor(.white)
.font(.system(size: 20))
}
.frame(width: 60, height: 60)
.padding()
Spacer()
}
@ -249,4 +276,20 @@ struct CustomMediaPlayer: View {
currentTime = player.currentTime().seconds
}
}
}
private func addPeriodicTimeObserver(fullURL: String) {
let interval = CMTime(seconds: 1.0, preferredTimescale: CMTimeScale(NSEC_PER_SEC))
timeObserverToken = player.addPeriodicTimeObserver(forInterval: interval, queue: .main) { time in
guard let currentItem = player.currentItem,
currentItem.duration.seconds.isFinite else {
return
}
let currentTime = time.seconds
let duration = currentItem.duration.seconds
UserDefaults.standard.set(currentTime, forKey: "lastPlayedTime_\(fullURL)")
UserDefaults.standard.set(duration, forKey: "totalTime_\(fullURL)")
}
}
}

View file

@ -36,13 +36,13 @@ class VideoPlayerViewController: UIViewController {
let lastPlayedTime = UserDefaults.standard.double(forKey: "lastPlayedTime_\(fullUrl)")
if lastPlayedTime > 0 {
let seekTime = CMTime(seconds: lastPlayedTime, preferredTimescale: 1)
self.player?.seek(to: seekTime) { _ in
self.player?.play()
}
} else {
self.player?.play()
}
let seekTime = CMTime(seconds: lastPlayedTime, preferredTimescale: 1)
self.player?.seek(to: seekTime) { _ in
self.player?.play()
}
} else {
self.player?.play()
}
}
override func viewDidAppear(_ animated: Bool) {
@ -51,28 +51,28 @@ class VideoPlayerViewController: UIViewController {
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
if let timeObserverToken = timeObserverToken {
player?.removeTimeObserver(timeObserverToken)
self.timeObserverToken = nil
}
}
func addPeriodicTimeObserver(fullURL: String) {
guard let player = self.player else { return }
let interval = CMTime(seconds: 1.0, preferredTimescale: CMTimeScale(NSEC_PER_SEC))
timeObserverToken = player.addPeriodicTimeObserver(forInterval: interval, queue: .main) { time in
guard let currentItem = player.currentItem,
currentItem.duration.seconds.isFinite else {
return
}
let currentTime = time.seconds
let duration = currentItem.duration.seconds
UserDefaults.standard.set(currentTime, forKey: "lastPlayedTime_\(fullURL)")
UserDefaults.standard.set(duration, forKey: "totalTime_\(fullURL)")
}
}
super.viewDidDisappear(animated)
if let timeObserverToken = timeObserverToken {
player?.removeTimeObserver(timeObserverToken)
self.timeObserverToken = nil
}
}
func addPeriodicTimeObserver(fullURL: String) {
guard let player = self.player else { return }
let interval = CMTime(seconds: 1.0, preferredTimescale: CMTimeScale(NSEC_PER_SEC))
timeObserverToken = player.addPeriodicTimeObserver(forInterval: interval, queue: .main) { time in
guard let currentItem = player.currentItem,
currentItem.duration.seconds.isFinite else {
return
}
let currentTime = time.seconds
let duration = currentItem.duration.seconds
UserDefaults.standard.set(currentTime, forKey: "lastPlayedTime_\(fullURL)")
UserDefaults.standard.set(duration, forKey: "totalTime_\(fullURL)")
}
}
}

View file

@ -22,6 +22,8 @@ struct AnimeInfoView: View {
@State var isLoading: Bool = true
@State var showFullSynopsis: Bool = false
@State var animeID: Int?
@State private var selectedEpisode: String = ""
@State private var selectedEpisodeNumber: Int = 0
@AppStorage("externalPlayer") private var externalPlayer: String = "Default"
@ -138,6 +140,8 @@ struct AnimeInfoView: View {
EpisodeCell(episode: episodes[index], episodeID: index, imageUrl: anime.imageUrl, progress: progress, animeID: animeID ?? 0)
.onTapGesture {
selectedEpisode = episodes[index]
selectedEpisodeNumber = index + 1
fetchEpisodeStream(urlString: episodeURL)
}
}
@ -185,7 +189,15 @@ struct AnimeInfoView: View {
return
} else if externalPlayer == "Custom" {
DispatchQueue.main.async {
let customMediaPlayer = CustomMediaPlayer(urlString: streamUrl)
let customMediaPlayer = CustomMediaPlayer(
urlString: streamUrl,
fullUrl: fullURL,
title: anime.name,
episodeNumber: selectedEpisodeNumber,
onWatchNext: {
selectNextEpisode()
}
)
let hostingController = UIHostingController(rootView: customMediaPlayer)
hostingController.modalPresentationStyle = .fullScreen
Logger.shared.log("Opening custom media player with url: \(streamUrl)")
@ -212,6 +224,17 @@ struct AnimeInfoView: View {
}
}
private func selectNextEpisode() {
guard let currentEpisodeIndex = episodes.firstIndex(of: selectedEpisode) else { return }
let nextEpisodeIndex = currentEpisodeIndex + 1
if nextEpisodeIndex < episodes.count {
selectedEpisode = episodes[nextEpisodeIndex]
selectedEpisodeNumber = nextEpisodeIndex + 1
let nextEpisodeURL = "\(module.module[0].details.baseURL)\(episodes[nextEpisodeIndex])"
fetchEpisodeStream(urlString: nextEpisodeURL)
}
}
private func openSafariViewController(with urlString: String) {
guard let url = URL(string: anime.href.hasPrefix("http") ? anime.href : "\(module.module[0].details.baseURL)\(anime.href)") else {
Logger.shared.log("Unable to open the webpage")

View file

@ -24,8 +24,13 @@ struct CircularProgressBar: View {
.rotationEffect(Angle(degrees: 270.0))
.animation(.linear, value: progress)
Text(String(format: "%.0f%%", min(progress, 1.0) * 100.0))
.font(.system(size: 12))
if progress >= 0.95 {
Image(systemName: "checkmark")
.font(.system(size: 12))
} else {
Text(String(format: "%.0f%%", min(progress, 1.0) * 100.0))
.font(.system(size: 12))
}
}
}
}
}

View file

@ -78,21 +78,23 @@ struct EpisodeCell: View {
}
do {
if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any],
let episodes = json["episodes"] as? [String: Any],
let episodeDetails = episodes["\(episodeID + 1)"] as? [String: Any],
let title = episodeDetails["title"] as? [String: String],
let image = episodeDetails["image"] as? String {
DispatchQueue.main.async {
self.episodeTitle = title["en"] ?? ""
self.episodeImageUrl = image
self.isLoading = false
}
} else {
print("Invalid response")
DispatchQueue.main.async {
self.isLoading = false
}
let jsonObject = try JSONSerialization.jsonObject(with: data, options: [])
guard let json = jsonObject as? [String: Any],
let episodes = json["episodes"] as? [String: Any],
let episodeDetails = episodes["\(episodeID + 1)"] as? [String: Any],
let title = episodeDetails["title"] as? [String: String],
let image = episodeDetails["image"] as? String else {
print("Invalid response format")
DispatchQueue.main.async {
self.isLoading = false
}
return
}
DispatchQueue.main.async {
self.episodeTitle = title["en"] ?? ""
self.episodeImageUrl = image
self.isLoading = false
}
} catch {
print("Failed to parse JSON: \(error)")
@ -102,4 +104,4 @@ struct EpisodeCell: View {
}
}.resume()
}
}
}