3

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")
}
Iam Wayne
  • 561
  • 6
  • 26
  • 1
    Once you save your recording you'll have to package that and insert it into your table view via UITableView's delegate and data source methods. I'd say figure out how to save the recording first write that method and then if you're having trouble creating a data model or inserting items into UITableView then just ask a new question. Check out this post for saving audio recordings: https://stackoverflow.com/questions/39433639/how-to-save-recorded-audio-ios – butter_baby Jun 21 '17 at 21:25
  • 1
    @buttler_baby Thank you for your response, that link helped me out a lot. But Once the data is save I know how to show the data in tableview. Just dont know how to actually save multiple recordings. Any suggestions? – Iam Wayne Jun 21 '17 at 22:11
  • 1
    Change the `soundFileUrl` Name and you will create a new audio file. For example sound1.caf, sound2.caf, sound3.caf – zsteed Jun 21 '17 at 22:20
  • 1
    @IamWayne You'll continually overwrite the same file your saving because it keeps getting saved with the same name. So I'd suggest doing something like: let audioRecording = NSUUID().UUIDString + ".m4a" so you always get a unique file name. – butter_baby Jun 21 '17 at 22:50
  • 1
    @zsteed thanks for your response, but how would I create a different file name for each recorded audio? Would it be better if I can create an array to hold the recorded files? – Iam Wayne Jun 21 '17 at 23:41
  • @ butler_baby thanks for your help and I know this might be a dumb question. But where should I put that line of code? – Iam Wayne Jun 21 '17 at 23:44
  • Basically, put the code that is currently in your `viewDidLoad` and put it in its own function. Then when you tap the `recordButton` you call that function. Use @butter_baby implementation and do this `let soundFileUrl = dirPath[0].appendingPathComponent(NSUUID().UUIDString + ".m4a")` – zsteed Jun 22 '17 at 15:36
  • Is your problem solved? You have working answers here. – Mozahler Jul 11 '17 at 14:32

1 Answers1

2

The reason you can only save one video is that you only specified one file name. If you want to keep multiple videos, you have to use different file names. You can ask the user to enter video file name and then store them. You can check if a video with same name exists or not in this way.

You have to store all your video files into document folder so that when user close and reopen the app, the video files are still there. An array of videos are stored in the memory of your phone and when the app is closed, you lose everything.

After you stored all your video files in document folder, on start up of your video list view controller, you can use this method to get a list of video names from the document folder and then display the name in the table view.

Fangming
  • 24,551
  • 6
  • 100
  • 90