Use AVPlayer for multiple videos

I'm developing a tutorial style tvOS app with multiple videos. The examples I've seen so far deal with only one video.

Defining the player and source(url) before body view

let avPlayer = AVPlayer(url: URL(string: "https://domain.com/.../.../video.mp4")!))

and then in the body view the video is displayed

VideoPlayer(player: avPlayer)

This allows options such as stop/start etc.

When I try something similar with a video title passed into this view I can't define the player with this title variable.

var vTitle: String
var avPlayer = AVPlayer(url: URL(string: "https://domain.com/.../.../" + vTitle + ".mp4"")!))
    
    var body: some View {
        

I het an error that vTitle can't be used in the url above the body view.

Any thoughts or suggestions? Thanks

Answered by DTS Engineer in 818810022

Hello @Boomer,

In the code snippet you shared, vTitle and avPlayer are both instance members of the same type (whatever your View type is here). You can't use an instance member in a property initializer.

You could do something like this:

struct MyView: View {
    
    let vTitle: String
    let avPlayer: AVPlayer
    
    init(vTitle: String) {
        self.vTitle = vTitle
        self.avPlayer = AVPlayer(url: URL(string: "https://domain.com/.../.../" + vTitle + ".mp4")!)
    }
    
    var body: some View {
        VStack {
            Text(vTitle)
            VideoPlayer(player: avPlayer)
        }
    }
}

I say could, because it's not clear to me if that code has the exact behavior you want (because I don't know what the exact behavior you want in your app is), but it does compile and may give you some ideas on how to implement the behavior you do want :)

-- Greg

Hello @Boomer,

In the code snippet you shared, vTitle and avPlayer are both instance members of the same type (whatever your View type is here). You can't use an instance member in a property initializer.

You could do something like this:

struct MyView: View {
    
    let vTitle: String
    let avPlayer: AVPlayer
    
    init(vTitle: String) {
        self.vTitle = vTitle
        self.avPlayer = AVPlayer(url: URL(string: "https://domain.com/.../.../" + vTitle + ".mp4")!)
    }
    
    var body: some View {
        VStack {
            Text(vTitle)
            VideoPlayer(player: avPlayer)
        }
    }
}

I say could, because it's not clear to me if that code has the exact behavior you want (because I don't know what the exact behavior you want in your app is), but it does compile and may give you some ideas on how to implement the behavior you do want :)

-- Greg

Use AVPlayer for multiple videos
 
 
Q