Reputation: 81
I'm trying to upload an audio that I recorded to a Firebase database. The recording is working fine, and the audio is also playing, I just need to upload it and also download it to the other users, so they can listen to it. The app itself is already sending text messages and they are working without any problem, the users can already chat among them.
This is were I record the audio (an audio recording session is already opened).
@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)
}
}
And this is how I get the file 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")
}
Now I need to get this file URL and upload it to Firebase, and download it on the other users app.
I'm using this method to retrieve the text messages from the 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
}
Thanks for the attention guys!
Upvotes: 2
Views: 4222
Reputation: 81
I solved the problem, my upload method now it's like this:
@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)
}
}
}
}
Upvotes: 1