簡體   English   中英

使用 Swift 將錄音上傳到 Firebase

[英]Uploading recording to Firebase with Swift

我一直在嘗試在用戶停止錄制到 Firebase 后立即上傳錄音。 但除了創建一個名為“audio”的新文件夾外,它什么也沒做。

我用於開始和停止錄制的代碼

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

我用於上傳到 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
            }
        }
    }
  }

請幫我!

嘗試:

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

所以我已經為此工作了幾個小時,這是我的答案:


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

我在編碼方面相對較新並且仍在學習。 這樣我的回答可能不是最好的和最短的。 但這對我有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM