Audio Player takes a while to load

I have the following code

         var downloadTask = URLSessionDownloadTask()
        downloadTask = URLSession.shared.downloadTask(with: url, completionHandler: { (url, response, error) in
            self.play(url: url!)
        })
        downloadTask.resume()


 func play (url: URL) {
        do {
            audioPlayer = try AVAudioPlayer(contentsOf: url as URL)
            audioPlayer.prepareToPlay()
            audioPlayer.volume = 1.0
            audioPlayer.enableRate = true
            
            updateCC()
            isReadyToPlay = true
            
            DispatchQueue.main.sync {
                self.remainingTimeLabel.text = self.stringFromTimeInterval(interval: audioPlayer.duration)
                
                self.slider.minimumValue = 0.0
                self.slider.maximumValue = Float(audioPlayer.duration)
                self.slider.setValue(0.0, animated: true)
                
                self.titleLabel.text = self.book.title
                self.artistLabel.text = self.book.author
                self.imageView.sd_setImage(with: URL(string: self.book.image as! String), placeholderImage: nil)
                self.imageView.layer.shadowColor = UIColor.gray.cgColor
                self.imageView.layer.shadowOpacity = 0.3
                self.imageView.layer.shadowOffset = CGSize(width: 4, height: 4)
                self.imageView.layer.shadowRadius = 5
                self.imageView.layer.masksToBounds = false
                
                NetworkActivityIndicatorManager.networkOperationFinished()
                LoadingIndicatorView.hide()
            }
            
        } catch let error as NSError {
            let params = [
                "Error Message": "Audio: \(error.localizedDescription)",
                "Method": "Audio",
                "UserId": MUser.sharedInstance.userId
            ];
            Flurry.logEvent("Error", withParameters: params);
            
        } catch {
            let params = [
                "Error Message": "AVAudio init failed",
                "Method": "Audio",
                "UserId": MUser.sharedInstance.userId
            ];
            Flurry.logEvent("Error", withParameters: params);
        }
    }

When I transition to the screen where the audio player loads, it takes a while to load/play the audio. Is there a way to stream the audio? or make it load faster.

1 answer

  • answered 2020-07-11 13:49 Frankenstein

    You might wanna do the AVAudioPlayer(contentsOf:) in the background queue. Here how you do this:

    func play (url: URL) {
           do {
            URLSession.shared.dataTask(with: url) { (data, _, _) in
                self.audioPlayer = try AVAudioPlayer(data: data)
                self.audioPlayer.prepareToPlay()
                //...
            }.resume()
        }
    }