Implementing Auto-Play Functionality for videos similar to Twitter/X

1.7k Views Asked by At

Right now, I am experimenting with AVKit and its media player attributes. I am trying to implement an auto-play functionality for videos in a feed view similar to what Twitter/X has.

Here is some code to show:

import SwiftUI
import AVKit

struct VideoPlayerView: View {
    
    @StateObject private var viewModel: VideoPlayerViewModel
    
    init(url: URL) {
        _viewModel = StateObject(wrappedValue: .init(url: url))
    }
    
    var body: some View {
        VStack {
            if let player: AVPlayer = viewModel.player {
                VideoPlayer(player: player)
                    .onAppear {
                        // Start playing or resume from the last known position
                        if let lastKnownTime = viewModel.lastKnownTime {
                            player.seek(to: CMTime(seconds: lastKnownTime, preferredTimescale: 600))
                        }
                        player.play()
                    }
                    .onDisappear {
                        // Pause the video and store the last known time
                        viewModel.lastKnownTime = player.currentTime().seconds
                        player.pause()
                    }
            }
        }
        .maxSize()
    }
}

class VideoPlayerViewModel: ObservableObject {
    @Published var player: AVPlayer?
    @Published var lastKnownTime: Double? // Store the last known playhead position
    
    init(url: URL) {
        player = AVPlayer(url: url)
        lastKnownTime = nil
    }
}

As you can see, I got the first part down where whenever a user scrolls down a feed and comes across a post with a video the video starts playing. However, I am having an issue with having the video continue playing when the user taps on the post to view its contents in its entirety. Currently, when the user taps on the post, the video plays from the beginning and overlaps with the initial video, making it sound like two different videos at the same time. How can I make it like Twitter/X so that the video just continues playing from where it was left off when the post is tapped on?

0

There are 0 best solutions below