使用multipartformdata将音频录制快速上传到服务器

时间:2020-09-01 22:06:12

标签: swift alamofire multipartform-data audio-recording

我正在尝试使用像这样的多格式数据将音频录制快速上传到服务器:

@objc func recordAudioButtonTapped(_ sender: UIButton) {
    if audioRecorder == nil {
        startRecording()
    } else {
        finishRecording(success: true)
    }
}
func startRecording() {
    let audioFilename = getFileURL()
    let settings = [
        AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
        AVSampleRateKey: 12000,
        AVNumberOfChannelsKey: 1,
        AVEncoderAudioQualityKey: AVAudioQuality.min.rawValue
    ]
    
    do {
        audioRecorder = try AVAudioRecorder(url: audioFilename, settings: settings)
        audioRecorder.delegate = self
        audioRecorder.record()
        recordButton.setTitle("Tap to Stop", for: .normal)
        uploadButton.isEnabled = true
    } catch {
        finishRecording(success: false)
    }
}

func finishRecording(success: Bool) {
    uploadButton.setTitle("Save", for: .normal)
    audioRecorder.stop()
    audioRecorder = nil
    
    if success {
        recordButton.setTitle("Tap to Re-record", for: .normal)
    } 
    else {
        recordButton.setTitle("Tap to Record", for: .normal)
        uploadButton.setTitle("Save", for: .normal)
       
    }
    uploadButton.setTitle("Save", for: .normal)
    uploadButton.isEnabled = true
    recordButton.isEnabled = true
}

func getDocumentsDirectory() -> URL {
    let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    return paths[0]
}
func getFileURL() -> URL {
    let path = getDocumentsDirectory().appendingPathComponent("recording.m4a")
    return path as URL
}

我在这里上传文件。API调用的响应表明文件已上传,但是当我在邮递员上检查它时,它没有显示文件。

multipartFormData.append(self.getFileURL(),
withName: "file_path",
fileName: "file.m4a",
mimeType: "audio/mpeg")

如果您有更轻松的方式记录和上传文件,请帮助我。谢谢

0 个答案:

没有答案