UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Problem with making AVPlayer observable?

Forums > SwiftUI

Hi all, I am creating the app and I have hit a roadblock which I cannot seem to solve. Because my app needs to play different kinds of audio, either a radio stream or a ready-made MP3 file, I have decided to use AVPlayer for the task, since it can play the remote content. And so I have made a class wrapping the AVPlayer like so:

import Foundation
import AVKit
class AVPlayerObservable: ObservableObject {
    @Published var player: AVPlayer? = nil
    public init() {

    }
}

I wrapped the class as I want to inject it into the environment. Never mind though, because after that I have written a view like so:

import AVKit
import Foundation
import SwiftUI
struct PodcastPlayerView: View {
    @EnvironmentObject var player: AVPlayerObservable
    init(url: URL) {
        if player.player == nil {
            player.player = AVPlayer(url: url)
        }
        else {
            player.player?.pause()
            player.player?.replaceCurrentItem(with: AVPlayerItem(url: url))
        }
    }
    var body: some View {
        Text("Test test test")
    }
}

And finally I call this test view like so:

Button("Listen") {
                PodcastPlayerView(url: URL(string: "https://tyflopodcast.net/pobierz.php?id=100&plik=0")!)
            }

Of course, I also have injected my wrapper into the environment like so:

ContentView().environment(\.managedObjectContext, dataController.container.viewContext).environmentObject(api).environmentObject(player)

And finally to the interesting part, after tapping on the view XCode crashes with the following error:

SwiftUI/EnvironmentObject.swift:70: Fatal error: No ObservableObject of type AVPlayerObservable found. A View.environmentObject(_:) for AVPlayerObservable may be missing as an ancestor of this view. (lldb) What the check? Sorry if I am stupid but I am banging my head for a few hours now and i cannot find the solution, and my app is almost complete!!!

2      

ContentView()
  .environment(\.managedObjectContext, dataController.container.viewContext)
  .environmentObject(api)
  .environmentObject(player)

What is player? In your app struct, do you have something like this?

@StateObject var player = AVPlayerObservable()

You need to instantiate an object to observe before you can pass it down through the environment.

Even with that correction, however, this might not work the way you want it to. The problem is that AVPlayer is a class (a.k.a. a reference type) and @Published doesn't work well (or, often, at all) with reference types; you need to use a value type like a struct. Never having played around with AVPlayer, though, I can't say for certain.

2      

I still cannot solve my problem; didn't think playing a remote MP3 will be so hard lol.

2      

@Bnerd  

Using roosterboy's hints, (i.e. you need to refer to a struct and not to a class), the following works (adjust your code as required)

Your model:

import Foundation
import AVKit
var audioPlayer: AVPlayer!
class AVPlayerObservable: ObservableObject {
    @Published var playerX = PlaySound()
    public init() {

    }

    struct PlaySound {

        func playSound(url: String) {

            do {

                audioPlayer = AVPlayer(url: URL(string: url)!)
                audioPlayer.play()
            }

        }
    }

}

Sample call :

import SwiftUI

struct ContentView: View {
    @StateObject var player = AVPlayerObservable()
    var body: some View {
        VStack {
            Button("Listen to me") {
                player.playerX.playSound(url: "https://transom.org/wp-content/uploads/2004/03/200206.hodgman8.mp3")
            }
        }.environmentObject(player)
        .padding()
    }
}

You could try to use the above as required to modify your code, the above works, although maybe is not exactly what you are looking for.

2      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.