skip to Main Content

I’m trying to download a URL from Firebase storage and save it to an AVAudioPlayer

func loadAudio(post: CompPost, completion: @escaping (AVAudioPlayer) -> ())
    {
        let audioRef = Storage.storage().reference().child("cPosts").child(post.uid).child("Audio").child(post.mp3)
        audioRef.downloadURL
        { (url, error) in
            print("mp3filename: " + post.mp3)
            guard error == nil else
            {
                print(error!.localizedDescription)
                return /**alert**/ }
            let audioURL = url
            print("url:" + audioURL!.absoluteString)
            do
            {
                try self.audioPlayer = AVAudioPlayer(contentsOf: audioURL!)
                completion(self.audioPlayer)
                print("THIS HAS LOADED")
            }
            catch
            {
                print("COULD NOT ASSIGN URL") /**alert**/
                //ERROR here that keeps on happening :(
            }
        }
    }

I know for a fact it’s the correct file from storage, and that there’s no error getting the url because of my print statements to check, however, for some reason there is an issue setting this URL to the contents of my AVAudioPlayer, audioPlayer

2

Answers


  1. instead of:

    try self.audioPlayer = AVAudioPlayer(contentsOf: audioURL!)
    

    try using this (note the try position):

     do {
        self.audioPlayer = try AVAudioPlayer(contentsOf: audioURL!)
        completion(self.audioPlayer)
    } catch {
        print("===> " + error.localizedDescription)
    }
    

    you can of course use AVPlayer as well (without the do/catch)

    Login or Signup to reply.
  2. What @jnpdx meant (I think is) – this way you can let iOS stream directly from the remote URL, without handling downloading the file yourself

    func loadAudio(post: CompPost, completion: @escaping (AVAudioPlayer) -> ())
    {
        let audioRef = Storage.storage().reference().child("cPosts").child(post.uid).child("Audio").child(post.mp3)
        audioRef.downloadURL
        { (url, error) in
            print("mp3filename: " + post.mp3)
            guard error == nil else
            {
                print(error!.localizedDescription)
                return /**alert**/ }
            let audioURL = url
            print("url:" + audioURL!.absoluteString)
            do
            {
                **try self.audioPlayer = AVPlayer(url: audioURL!)**
                completion(self.audioPlayer)
                print("THIS HAS LOADED")
            }
            catch
            {
                print("COULD NOT ASSIGN URL - Error = /(error)") /**alert**/
                //ERROR here that keeps on happening :(
            }
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search