简体   繁体   中英

Uploading recording to Firebase with Swift

I've been trying to upload audio recording right after user stops recording to the Firebase. But it doesn't do anything apart from creating a new folder named "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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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