I am new to Swift, so any help would be gladly appreciated. I am creating this project to record, save recorded data and show data in table view. Right now I can record and play only the current recording. If I press record again the previous recorded audio will be deleted. But I want to save the recorded audio permanently and show in table view. This is what I got so far. Thanks in advance!
import UIKit
import AVFoundation
class ViewController: UIViewController, AVAudioPlayerDelegate,
AVAudioRecorderDelegate {
var audioPlayer: AVAudioPlayer?
var audioRecorder: AVAudioRecorder?
@IBOutlet weak var recordAudio: UIButton!
@IBOutlet weak var stopAudio: UIButton!
@IBOutlet weak var playAudio: UIButton!
var arrayData: [FileManager] = []
override func viewDidLoad() {
super.viewDidLoad()
playAudio.isEnabled = false
stopAudio.isEnabled = false
// Creating File Manager
let fileMgr = FileManager.default
let dirPath = fileMgr.urls(for: .documentDirectory, in: .userDomainMask)
let soundFileUrl = dirPath[0].appendingPathComponent("sound.caf")
let recordSettings = [AVEncoderAudioQualityKey: AVAudioQuality.min.rawValue,
AVEncoderBitRateKey: 16,
AVNumberOfChannelsKey: 2,
AVSampleRateKey: 44100.0 ] as [String:Any]
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord)
} catch {
print(error.localizedDescription)
}
do {
try audioRecorder = AVAudioRecorder(url: soundFileUrl, settings: recordSettings as [String : Any])
audioRecorder?.prepareToRecord()
} catch {
print(error.localizedDescription)
}
}
@IBAction func recordButton(_ sender: Any) {
if audioRecorder?.isRecording == false {
playAudio.isEnabled = false
stopAudio.isEnabled = true
audioRecorder?.record()
}
}
@IBAction func stopButton(_ sender: Any) {
stopAudio.isEnabled = false
playAudio.isEnabled = true
recordAudio.isEnabled = true
if audioRecorder?.isRecording == true{
audioRecorder?.stop()
} else {
audioPlayer?.stop()
}
}
@IBAction func playButton(_ sender: Any) {
if audioRecorder?.isRecording == false{
stopAudio.isEnabled = true
recordAudio.isEnabled = true
do {
try audioPlayer = AVAudioPlayer(contentsOf: (audioRecorder?.url)!)
audioPlayer!.delegate = self
audioPlayer!.prepareToPlay()
audioPlayer!.play()
} catch {
print(error.localizedDescription)
}
}
}
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
recordAudio.isEnabled = true
stopAudio.isEnabled = false
}
func audioPlayerDecodeErrorDidOccur(_ player: AVAudioPlayer, error: Error?) {
print("Audio Player Error")
}
func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
}
func audioRecorderEncodeErrorDidOccur(_ recorder: AVAudioRecorder, error: Error?) {
print("Audio Recorder Error")
}