简体   繁体   English

如何使用 Swift 5 /SwiftUI 将 AVAudioRecorder 文件上传到 Firebase 存储?

[英]How to upload AVAudioRecorder files to Firebase Storage with Swift 5 /SwiftUI?

Hi I know this have been asked a few times but I am needing help with uploading user voice recordings to Firebase.嗨,我知道这已被问过几次,但我需要帮助将用户录音上传到 Firebase。 When the user records their audio in the app and press the stop button I want the recording to be uploaded and stored in Firebase instead of the user's phone.当用户在应用程序中录制他们的音频并按下停止按钮时,我希望将录音上传并存储在 Firebase 而不是用户的手机中。

Heres the function for recording这是用于录制的 function

func startRecording() {
    
    let recordingSession = AVAudioSession.sharedInstance()
    
    do {
        try recordingSession.setCategory(.playAndRecord, mode: .default)
        try recordingSession.setActive(true)
    } catch {
        print("Failed to set up recording session")
    }
    let documentPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
    let audioFilename = documentPath.appendingPathComponent("\(Date().toString(dateFormat: "dd-MM-YY_'at'_HH:mm:ss")).m4a")
    let settings = [
        AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
        AVSampleRateKey: 12000,
        AVNumberOfChannelsKey: 1,
        AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
    ]
    
    do {
        audioRecorder = try AVAudioRecorder(url: audioFilename, settings: settings)
        audioRecorder.record()
        
        recording = true
    } catch {
        print("Could not start recording")
    }
}

Here is the function when the user stops recording这是用户停止录制时的 function

func saveRecording() {
    
    let path = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
       let directoryContents = try! FileManager.default.contentsOfDirectory(at: path, includingPropertiesForKeys: nil)

       for i in directoryContents {
        user.answersSent.append(CardModel(fullname: question.fullname, username: question.username, imageURL: question.imageURL, question: question.question, fileURL: i, createdAt: getCreationDate(for: i), colorChoice: question.colorChoice))
       }
   
      
            
            user.answersSent.sort(by: { $0.createdAt?.compare($1.createdAt!) == .orderedDescending})
           
            
        
        }
    }
    

Thank you so much for taking the time to read.非常感谢您花时间阅读。 I spent almost two days trying to figure it out.我花了将近两天的时间试图弄清楚。

  1. Instead of letting your URL go out of scope immediately, store it in a property on whatever class is running this functions (if you're doing this in a View , move all of the recording logic to an ObservableObject ). Instead of letting your URL go out of scope immediately, store it in a property on whatever class is running this functions (if you're doing this in a View , move all of the recording logic to an ObservableObject ).

  2. At the end of the recording, now that you have the URL, you won't have to do the createdAt sorting, which I assume maybe you're doing to get the most recent file (it's a little unclear to me at this point).在录制结束时,既然您有了 URL,您就不必进行createdAt排序,我假设您可能正在这样做以获得最新的文件(此时我有点不清楚) .

  3. Upload the local file using the method described in the Firebase documentation ( https://firebase.google.com/docs/storage/ios/upload-files#upload_from_a_local_file ):使用 Firebase 文档 ( https://firebase.google.com/docs/storage/ios/upload-files#upload_from_a_local_file ) 中描述的方法上传本地文件:

// File located on disk
// Create a reference to the file you want to upload
let audioFileRef = storageRef.child("audioFiles/audioFile.m4a") //adjust this to have a unique name

let uploadTask = audioFileRef.putFile(from: localAudioURL, metadata: nil) { metadata, error in
  guard let metadata = metadata else {
    // Uh-oh, an error occurred!
    return
  }
  //optionally, delete original local file here
}
  1. Optionally, delete your local file upon completion of the upload.或者,在上传完成后删除您的本地文件。 Also, you could choose to use the temporary directory rather than the documents directory to store the initial recording in the first place.此外,您可以选择使用临时目录而不是文档目录来首先存储初始记录。

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

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