Iam Wayne
Iam Wayne

Reputation: 561

Swift 3 Play audio downloaded from Firebase

I am new to Swift, I managed to download the audio from firebase and stored it locally, but dont know how to play with AVAudioPlayer. Any help would be appreciated. This is what I got so far.

class FireBaseViewController: UIViewController {

     var audioPlayer:AVAudioPlayer = AVAudioPlayer()

    override func viewDidLoad() {
        super.viewDidLoad()


        let storageRef = FIRStorage.storage().reference()

        let files = storageRef.child("Audio/Self Commitment.m4a")

        let localURL: NSURL! = NSURL(fileURLWithPath:"/Users/wayne/Desktop/Playground/Audio/Self Commitment.m4a")

        let downloadTask = files.write(toFile: localURL as URL) { (URL, error) -> Void in
                        if (error != nil) {
                            print("Uh-oh, an error occurred!")
                        } else {
                             print("Local file URL for  is returned")
                        }
                    }

                let audioPath = localURL

        do {

            try audioPlayer = AVAudioPlayer(contentsOf:URL(fileURLWithPath: audioPath))

        }   catch {print("file is unavilable")

        }
       audioPlayer.play()

    }

    }

Upvotes: 3

Views: 3351

Answers (3)

user12208004
user12208004

Reputation: 1988

I had the same problem. Michel's answer helped me. You don't have to use FileManager although you may need cache system.

https://stackoverflow.com/a/51733033/12208004

func preparePlayer() {
        guard let url = URL(string: "https://yourURL.mp3") else {
            print("Invalid URL")
            return
        }
        do {
            let session = AVAudioSession.sharedInstance()
            try session.setCategory(AVAudioSessionCategoryPlayback)
            let soundData = try Data(contentsOf: url)
            audioPlayer = try AVAudioPlayer(data: soundData)
            audioPlayer.prepareToPlay()
            audioPlayer.volume = 0.7
            audioPlayer.delegate = self
            let minuteString = String(format: "%02d", (Int(audioPlayer.duration) / 60))
            let secondString = String(format: "%02d", (Int(audioPlayer.duration) % 60))
            print("TOTAL TIMER: \(minuteString):\(secondString)")
        } catch {
            print(error)
        }
    }

Upvotes: 1

Grigory Bochkarev
Grigory Bochkarev

Reputation: 79

You can also play audio without downloading it. To do it you should:

1) Get a download url

2) Initiate AVPlayerItem with this url

3) Set player and play

Swift 4.2

let storage = Storage.storage()    
let storageReference = storage.reference(forURL: storagePath)
            storageReference.downloadURL { (hardUrl, error) in
                if error == nil, let url = hardUrl {
                    self.playerItem = AVPlayerItem(url: url)
                    self.playerInstance = AVPlayer(playerItem: self.playerItem)

Upvotes: 0

Eliezer Ferrá
Eliezer Ferrá

Reputation: 137

I had the same problem. What I did was used the FileManager to generate the URL where I would store my file

let fileURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent("file_name.mp3")

Then you can save the file and play it like this:

storeRef.getData(maxSize: 10 * 1024 * 1024) { (data, error) in
        if let error = error {
            print(error)
        } else {
            if let d = data {
                do {
                    try d.write(to: fileURL)
                    self.audioPlayer = try AVAudioPlayer(contentsOf: fileURL)
                    self.audioPlayer.play()
                } catch {
                    print(error)
                }
            }
        }
    }

I already tried it and it worked!

Upvotes: 4

Related Questions