2017-05-10 91 views
0

我是Swift的新手,我設法從firebase下載音頻並將其存儲在本地,但不知道如何使用AVAudioPlayer播放。任何幫助,將不勝感激。這是我到目前爲止。Swift 3播放從Firebase下載的音頻

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() 

    } 

    } 

回答

0

我有同樣的問題。我所做的就是使用文件管理器來生成在那裏我會存儲我的文件

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

然後就可以保存文件,播放這樣的網址:

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) 
       } 
      } 
     } 
    } 

我已經嘗試過了,它的工作!