使用 Swift 将录音上传到 Firebase

Posted

技术标签:

【中文标题】使用 Swift 将录音上传到 Firebase【英文标题】:Uploading recording to Firebase with Swift 【发布时间】:2018-07-29 07:33:56 【问题描述】:

我一直在尝试在用户停止录制到 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
            
        
    
  

请帮帮我!

【问题讨论】:

【参考方案1】:

试试:

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

【讨论】:

我收到错误“'ViewController' 类型的值没有成员 'recordedVoice'”。 @Joel 尝试像这样录制您的音频:Another method 好的,我会...谢谢 :) 如果可行,将在此处更新。

以上是关于使用 Swift 将录音上传到 Firebase的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 ASP.NET 和 C# 将录音上传到 Sound Cloud?

Swift 中的实时录音

Vue 录音实时上传,分析问题,解决问题,最后展示完整方案

swift 录音demo

Vue 录音实时上传,分析问题,解决问题,最后展示完整方案

Swift + AVAudioRecorder 非常安静地录制