1

I'm working on the audio player portion of my app and inside the player view, I have a simple if statement check. It looks to make sure there is an instance of the audioManager.player and if there is one, it created the vstacks/hstacks etc.

For some reason, it is failing on that check and saying there is no instance of the audioManager and not loading the appropriate view. Its not working with the simulator where I create the instance of AudioManager() on app start up and its not working in the preview either where I'm directly injecting the instance which makes no sense.

I do notice that .autoconnect() is white? I'm not sure if that means its not recognizing something or what.

Here is the code for the view player

import SwiftUI


struct listeningActivity: View {
    @EnvironmentObject var audioManager: AudioManager
    var listeningActivityVM:ListeningActivityViewModel
    
    @State private var value: Double = 0.0
    @State private var isEditing: Bool = false
    
    let timer = Timer.publish(every: 0.5, on: .main, in: .common)
        .autoconnect()
    
    
    var body: some View {
        
        ZStack{
            
            Image("pot")
                .resizable()
                .scaledToFill()
                .frame(width: UIScreen.main.bounds.width)
                .ignoresSafeArea()
            
            VStack(spacing: 32) {
                HStack {
                    Button {
                        
                    } label: {
                        Image(systemName: "xmark.circle.fill")
                            .font(.system(size:36))
                            .foregroundColor(.white)
                    }
                    
                    Spacer()
                }
                
                Text("pasta carbonoara")
                    .font(.title)
                    .foregroundColor(.white)
                
                Spacer()
                
                if let player = audioManager.player {
                    VStack(spacing: 5){
                        
                        Slider(value: $value, in: 0...player.duration) { editing
                            in
                            
                            print("editing", editing)
                            isEditing = editing
                            
                            if !editing {
                                player.currentTime = value
                            }
                        }
                        .scaleEffect(1.5)
                        .frame(width: 200, height: 20)
                        .tint(.orange)
                        .padding(.top, 50)
                        
                        HStack{
                            Text(DateComponentsFormatter.positional
                                .string(from: player.currentTime) ?? "0:00")
                            
                            Spacer()
                            
                            Text(DateComponentsFormatter.positional
                                .string(from: player.duration - player.currentTime) ?? "0:00")
                            
                        }.padding([.leading, .trailing], 40)
                            .padding(.top, 15)
                    }
                    
                    HStack{
                        PlaybackControlButton(systemName: "repeat") {
                            
                        }
                        Spacer()
                        PlaybackControlButton(systemName: "gobackward.10") {
                            
                        }
                        Spacer()
                        PlaybackControlButton(systemName: player.isPlaying ? "pause.circle.fill" : "play.circle.fill", fontSize: 44) {
                            audioManager.playPlause()
                        }
                        Spacer()
                        PlaybackControlButton(systemName: "goforward.10") {
                            
                        }
                        Spacer()
                        PlaybackControlButton(systemName: "stop.fill") {
                            
                        }
                    }
                }
                
            }
            .padding(20)
        }
        .onAppear{
            audioManager.startPlayer(track: listeningActivityVM.audioAct.track)
            
        }.onReceive(timer) { _ in
            guard let player = audioManager.player, !isEditing else {return}
            value = player.currentTime
        }
        
    }
}



struct listeningActivity_Previews: PreviewProvider {
    static let listeningActivityVM  = ListeningActivityViewModel(audioAct: audioActivty.data)
    static var previews: some View {
        listeningActivity(listeningActivityVM: listeningActivityVM)
            .environmentObject(AudioManager())
    }
}

This is my AudioManager() code

import Foundation
import AVKit

final class AudioManager: ObservableObject{
    
    var player: AVAudioPlayer?
    
    func startPlayer(track: String) {
        guard let url = Bundle.main.url(forResource: track, withExtension: "wav") else {
            print("Resource not found: \(track)")
            return
        }
        
        
        do {
            try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
            try AVAudioSession.sharedInstance().setActive(true)
            player = try AVAudioPlayer(contentsOf: url)
            
            player?.play()
        }catch{
            print("Fail to initialize player", error)
        }
    }
    
    func playPlause() {
        guard let player = player else {
            print("Instance of audio player not found")
            return
        }
        
        if player.isPlaying {
            player.pause()
        }else {
            player.play()
        }
    }
}
mzm0227
  • 43
  • 5

1 Answers1

1

I looked back at the YouTube tutorial I was following and luckily some people were having the same issue and solved the problem in the comments.

I needed to add the @Published property wrapper in front of my var player: AVAudioPlayer? declaration.

Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
mzm0227
  • 43
  • 5
  • If you have a new question, please ask it by clicking the [Ask Question](https://stackoverflow.com/questions/ask) button. Include a link to this question if it helps provide context. - [From Review](/review/low-quality-posts/34519216) – eglease Jun 09 '23 at 19:34
  • 1
    @eglease: This doesn't look like a new question, but rather an answer. That would be clearer, admittedly, if the author cleaned up the formatting to highlight the code. – Jeremy Caney Jun 10 '23 at 00:19