AVQueuePlayer/AVPlayer rate property is not being changed everytime I assign a new value to it.

I have used AVQueuePlayer in my music app to play sequence of audios from a remote server, this how I have defined things my player in my ViewModel

Variables

private var cancellables = Set<AnyCancellable>() private let audioSession = AVAudioSession.sharedInstance() private var avQueuePlayer: AVQueuePlayer? @Published var playbackSpeed: Float = 1.0

before starting playback, I am making sure that audio session is set properly, the code snippet used for that is

do { try audioSession.setCategory(.playback, mode: .default, options: []) try audioSession.setActive(true, options: []) } catch { return }

and this is the function I am using to update playback speed

func updatePlaybackSpeed(_ newSpeed: Float){ if newSpeed > 0.0, newSpeed <= 2.0{ playbackSpeed = newSpeed avQueuePlayer?.rate = newSpeed print("requested speed is (newSpeed) and actual speed is (String(describing: avQueuePlayer?.rate))") } }

sometimes whatever speed is set, player seems to play at the same speed as it was set, e.g. Once I got "requested speed is 1.5 and actual speed is 1.5", and player also seemed to play at the speed of 1.5 but another time I got "requested speed is 2.0 and actual speed is 2.0", but player still seemed to play at the speed of 1.0

to observe changes in rate, I used this

**private func observeRateChanges() { guard let avQueuePlayer = self.avQueuePlayer else { return }

NotificationCenter.default.publisher(for: AVQueuePlayer.rateDidChangeNotification, object: avQueuePlayer)
    .compactMap { $0.userInfo?[AVPlayer.rateDidChangeReasonKey] as? AVPlayer.RateDidChangeReason }
    .sink { reason in
        switch reason {
        case .appBackgrounded:
            print("The app transitioned to the background.")
        case .audioSessionInterrupted:
            print("The system interrupts the app’s audio session.")
        case .setRateCalled:
            print("The app set the player’s rate.")
        case .setRateFailed:
            print("An attempt to change the player’s rate failed.")
        default:
            break
        }
    }
    .store(in: &cancellables)

}**

when rate was set properly, I got this "The app set the player’s rate." from the above function, but when it wasn't, I got this "An attempt to change the player’s rate failed.,"

now I am not able to understand why rate is not being set, and if it gave "requested speed is 2.0 and actual speed is 2.0" from updatePlaybackSpeed function, why does the player seems to play with the speed of 1.0?

AVQueuePlayer/AVPlayer rate property is not being changed everytime I assign a new value to it.
 
 
Q