Changing the video playing in VideoPlayer programmatically

I'm using SwiftUI to play videos. I'm trying to use a NavigationStack to show a list of videos, then when i click on on it goes to a new view to play that video. I see lots of example that have the underlying AVPlayer in a @State or @StateObject, but as soon as I reassign it to a new AVPlayer the VideoPlayer stops working; I just get a black screen.

Is there a better way to change the url that VideoPlayer is playing? I'm trying to avoid creating a bunch of VideoPlayer objects ahead of time and having them all in memory, as this might have a large number of videos.

More details: App is TVOS 17, using Xcode 15.

Answered by Engineer in 768845022

One way to avoid creating a new player would be to reuse the player and replace its current item. Please refer to replaceCurrentItem(with:). You can create an AVPlayerItem using an URL with init(url:).

Accepted Answer

One way to avoid creating a new player would be to reuse the player and replace its current item. Please refer to replaceCurrentItem(with:). You can create an AVPlayerItem using an URL with init(url:).

Changing the video playing in VideoPlayer programmatically
 
 
Q