我正在尝试将我录制的音频上传到Firebase数据库。录音工作正常,音频也在播放,我只需要上传并下载到其他用户,这样他们就可以收听。该应用程序本身已经发送短信,他们正在工作没有任何问题,用户可以已经在他们之间聊天。
这是我录制的音频(录音会话已经打开)。
@IBAction func sendAudio(_ sender: Any) {
//Check if there is an active AudioRecorder
if audioRecorder == nil {
numberOfRecords += 1
let filename = getAudioFileURL()
let settings = [AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
AVSampleRateKey: 12000,
AVNumberOfChannelsKey: 2,
AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue]
//Start recording
do {
audioRecorder = try AVAudioRecorder(url: filename, settings: settings)
audioRecorder.delegate = self
audioRecorder.record()
audioButton.setTitle("Stop", for: .normal)
} catch {
alertsAudio(title: "Error", message: "Error!")
}
} else {
//Stop audio recording
audioRecorder.stop()
audioRecorder = nil
UserDefaults.standard.set(numberOfRecords, forKey: "myNumber")
messageTableView.reloadData()
audioButton.setTitle("Record", for: .normal)
}
}
这就是我获取文件URL的方式:
func getDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentDirectory = paths[0]
return documentDirectory
}
func getAudioFileURL() -> URL {
return getDirectory().appendingPathComponent(".m4a")
}
现在我需要获取此文件网址并将其上传到Firebase,然后在其他用户应用上下载。
我正在使用此方法从firebase中检索文本消息:
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
print("Worked!")
if messageTextfield.text == "" {
//o campo de mensagem está em branco
let alert = UIAlertController(title: "Error!!!!", message: "You can't send a message without text. Please type a message!", preferredStyle: .alert)
alert.addAction(UIKit.UIAlertAction(title: "Ok", style: .default, handler: nil))
self.present(alert, animated: true)
messageTextfield.becomeFirstResponder()
} else {
messageTextfield.isEnabled = false
sendButton.isEnabled = false
let messagesDB = Database.database().reference().child("Messages")
// if audioRecorder != nil{
// message = getDirectory().appendingPathComponent("\(numberOfRecords).m4a")
// } else {
// message = messageTextfield.text
// }
let messageDict = ["Sender": Auth.auth().currentUser?.email, "MessageBody": messageTextfield.text]
messagesDB.childByAutoId().setValue(messageDict) {
(error, reference) in
if (error) != nil {
print(error!)
} else {
print("Message sent!")
self.messageTextfield.isEnabled = true
self.sendButton.isEnabled = true
self.messageTextfield.text = ""
}
}
}
return true
}
感谢关注的人!
答案 0 :(得分:0)
我解决了这个问题,我的上传方法就像这样:
@IBAction func sendAudio(_ sender: Any) {
//Check if there is an active AudioRecorder
if audioRecorder == nil {
numberOfRecords += 1
let filename = getAudioFileURL()
let settings = [AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
AVSampleRateKey: 12000,
AVNumberOfChannelsKey: 2,
AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue]
//Start recording
do {
audioRecorder = try AVAudioRecorder(url: filename, settings: settings)
audioRecorder.delegate = self
audioRecorder.record()
audioButton.setTitle("Stop", for: .normal)
} catch {
alertsAudio(title: "Recording error", message: "Error in the audio recording.")
}
} else {
//Stopping the recording
SVProgressHUD.show()
audioRecorder.stop()
audioRecorder = nil
UserDefaults.standard.set(numberOfRecords, forKey: "myNumber")
messageTableView.reloadData()
audioButton.setTitle("Gravar", for: .normal)
let fileUrl = getAudioFileURL()
let storage = Storage.storage()
let metadata = StorageMetadata()
metadata.contentType = "audio/mp4"
let refStr = (Auth.auth().currentUser?.email)! + "|" + "\(NSUUID().uuidString)" + "|" + "recording.m4a"
let pathStr = "Messages/\(NSUUID().uuidString)/\(refStr)"
let uploadRef = storage.reference().child(pathStr)
uploadRef.putFile(from: fileUrl, metadata: nil) { metadata,
error in
if error == nil {
print("Successfully Uploaded Audio")
SVProgressHUD.dismiss()
let downloadUrl = (metadata?.downloadURL())!
print("URL: \(downloadUrl)")
//completion(fileUrl)
//let messagesDB = Database.database().reference().child("Messages")
//let key = messagesDB.childByAutoId().key
var messageInfoArray = refStr.components(separatedBy: "|")
let messageDict = ["Sender": messageInfoArray[0], "MessageBody": "recording-audioRecorded", "AudioURL": "\(pathStr)", "AudioID": messageInfoArray[1], "IsAudio": "\(NSUUID().uuidString)-True"]
let childUpdates = ["Mensagens/\(messageInfoArray[1])": messageDict]
Database.database().reference().updateChildValues(childUpdates)
}
else {
SVProgressHUD.dismiss()
print("UploadError \(String(describing: error?.localizedDescription))")
let alert = UIAlertController(title: "Error!!!", message: "The following error ocurred \(String(describing: error?.localizedDescription))", preferredStyle: .alert)
alert.addAction(UIKit.UIAlertAction(title: "Ok", style: .default, handler: nil))
self.present(alert, animated: true)
}
}
}
}