简体   繁体   English

使用 Swift 将录音上传到 Firebase

[英]Uploading recording to Firebase with Swift

I've been trying to upload audio recording right after user stops recording to the Firebase.我一直在尝试在用户停止录制到 Firebase 后立即上传录音。 But it doesn't do anything apart from creating a new folder named "audio".但除了创建一个名为“audio”的新文件夹外,它什么也没做。

Code I'm using for starting and stopping recording我用于开始和停止录制的代码

@IBAction func recordAudio(_ sender: AnyObject) {
    recordingLabel.text = "Recording in progress"
    stopRecordingButton.isEnabled = true
    recordButton.isEnabled = false

    let dirPath = NSSearchPathForDirectoriesInDomains(.documentDirectory,.userDomainMask, true)[0] as String
    let recordingName = "recordedVoice.wav"
    let pathArray = [dirPath, recordingName]
    let filePath = URL(string: pathArray.joined(separator: "/"))

    let session = AVAudioSession.sharedInstance()
    try! session.setCategory(AVAudioSessionCategoryPlayAndRecord, with:AVAudioSessionCategoryOptions.defaultToSpeaker)

    try! audioRecorder = AVAudioRecorder(url: filePath!, settings: [:])
    audioRecorder.delegate = self
    audioRecorder.isMeteringEnabled = true
    audioRecorder.prepareToRecord()
    audioRecorder.record()
}


@IBAction func stopRecording(_ sender: AnyObject) {
    print("Stop recording button was pressed")
    recordButton.isEnabled = true
    stopRecordingButton.isEnabled = false
    recordingLabel.text = "Tap to Record"
    audioRecorder.stop()
    let audioSession = AVAudioSession.sharedInstance()
    try! audioSession.setActive(false)
}

code I'm using for uploading to Firebase我用于上传到 Firebase 的代码

func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
        print("finished recording")


    let storageRef = Storage.storage().reference().child("audio/recordedVoice.wav")

    if let uploadData = AVFileType(self.recordedVoice.wav!) {

        storageRef.put(uploadData, metadata: nil) {(metadata, error) in

            if error != nil {
                print(error)
                return
            }
        }
    }
  }

Please help me!请帮我!

Try: 尝试:

 let audioName = NSUUID().uuidString //You'll get unique audioFile name
 let storageRef = Storage.storage().reference().child("audio").child(audioName)
 let metadata  = StorageMetadata()
 metadata.contentType = "audio/wav"
 if let uploadData = AVFileType(self.recordedVoice.wav!) {

        storageRef.putData(uploadData, metadata: metadata) { (metadata, err) in
            if err != nil {
                //print(err)
                return
            }
            if let _ = metadata?.downloadURL()?.absoluteString {
                print("uploading done!")
            }
        }
    }

so I have been working on this for hours and here is my answer:所以我已经为此工作了几个小时,这是我的答案:


 let referance = storage.reference()
        let mediaFolder = referance.child("media")
        let id = UUID().uuidString // using uuid to give uniq names to audiofiles preventing overwrite
        let mediaRef = mediaFolder.child(id + K.fileName) // creating file referance using uuid + filename
        let path = getFileURL() // getting filepath
        do {
            let data = try Data(contentsOf: path) // getting data from filepath
            mediaRef.putData(data) { metadata, error in
                if error != nil {
                    self.showAlert(title: "Error", message: error?.localizedDescription, cancelButtonTitle: "cancel", handler: nil)
                } else {
                    mediaRef.downloadURL { url, error in
                        let url = url?.absoluteString
                        print(url)
                    }
                }
            }
            print("record has come")
        } catch {
            print("error cant get audio file")
        }

I'm relatively new at coding and still learning.我在编码方面相对较新并且仍在学习。 So that my answer may not be the best and shortest.这样我的回答可能不是最好的和最短的。 But This worked for me.但这对我有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM