【问题标题】:How to upload AVAudioRecorder files to Firebase Storage with Swift 5 /SwiftUI?如何使用 Swift 5 /SwiftUI 将 AVAudioRecorder 文件上传到 Firebase 存储?
【发布时间】:2021-04-18 14:20:33
【问题描述】:

您好,我知道这个问题已经被问过几次了,但我在将用户录音上传到 Firebase 方面需要帮助。当用户在应用中录制他们的音频并按下停止按钮时,我希望将录音上传并存储在 Firebase 而不是用户的手机中。

这是录音功能

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

这是用户停止录制时的功能

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

非常感谢您花时间阅读。我花了将近两天的时间试图弄清楚。

【问题讨论】:

  • 您询问如何将文件上传到 Firebase 存储,但未包含任何 Firebase 代码。大局是,当您录制时,“文件”要么被写入内存或磁盘。当用户单击停止时,您希望将该文件从内存或磁盘上传到存储。 Firebase 入门指南Uploading files 对此进行了很好的介绍。那么除此之外,还有什么问题?您是否有一些您遇到困难的 Firebase 代码?

标签: swift firebase swiftui avaudiorecorder avkit


【解决方案1】:
  1. 不要让您的 URL 立即超出范围,而是将其存储在运行此函数的任何类的属性中(如果您在 View 中执行此操作,请将所有记录逻辑移动到 ObservableObject )。

  2. 在录制结束时,既然您有了 URL,您就不必进行 createdAt 排序,我假设您可能正在这样做以获得最新的文件(有点不清楚我现在)。

  3. 使用 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. (可选)上传完成后删除本地文件。此外,您可以选择使用临时目录而不是文档目录来存储初始记录。

【讨论】:

    猜你喜欢
    • 2020-12-10
    • 2020-07-10
    • 2017-07-03
    • 2020-04-08
    • 1970-01-01
    • 2019-09-06
    • 2020-12-22
    • 2020-05-07
    • 1970-01-01
    相关资源
    最近更新 更多