Record two seperate sounds using avsessions

I want to record 2 separate sounds. Right now my code can record 1 sound sound and play it but to record another sound it saves over the previous one. I have 2 separate buttons a and b where I would like to store each sound. I am only looking to record to separate sounds that save with something like userdefualts.

                    import UIKit
       import AVFoundation

     class ViewController: UIViewController, AVAudioPlayerDelegate, AVAudioRecorderDelegate {
@IBOutlet var A : UIButton?
@IBOutlet var B: UIButton?
// MARK: - Properties
var recorder: AVAudioRecorder!
var player: AVAudioPlayer!
var audioSession = AVAudioSession.sharedInstance()

// File properties
let fileName = "file.m4a"
var filePath = ""

override func viewDidLoad() {
    super.viewDidLoad()

    // 1 - Setup your file name
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-ddd HH:mm:ss"
    let dateTimeStamp = dateFormatter.string(from: Date())
    filePath = "recording-" + dateTimeStamp + "-" + fileName

    // 2 prepare a record session
    self.setupRecorder()

}

// MARK: - IBActions
@IBAction func recordAudio(_ sender: Any) {
    do{
        try audioSession.setCategory(AVAudioSessionCategoryRecord)
    }
    catch let err{
        print("Playback Error has occured: \(err)")
    }
    if recorder.isRecording{
        print("stopped recording")
        recorder.stop()
    }
    else{
        print("recording")
        recorder.record()
    }

}

@IBAction func playAudio(_ sender: Any) {
    do{
        try audioSession.setCategory(AVAudioSessionCategoryPlayback)
    }
    catch let err{
        print("Playback Error has occured: \(err)")
    }
    self.prepareAudioPlayer()

    if recorder.isRecording{
        recorder.stop()
    }

    if player.isPlaying{
        print("player is playing")
        player.currentTime = 0.0
    }
    else{
        print("player is playing")
        player.play()
           }
       }
           }

     extension ViewController{
// MARK: - Helper functions
func setupRecorder(){
    let settings = [AVFormatIDKey: kAudioFormatAppleLossless,
                    AVSampleRateKey: 12000,
                    AVNumberOfChannelsKey: 1,
                    AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue] as [String : Any]
    do {
        recorder = try AVAudioRecorder(url: getFileUrl(), settings: settings)
        recorder.record(forDuration: 30.0)
        recorder.delegate = self
    }
    catch let errr{
        print(errr)
    }
}

func getCacheDirectory() -> String{
    let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
    return path[0]
}

func getFileUrl() -> URL{
    let fileUrl = URL(fileURLWithPath: getCacheDirectory()).appendingPathComponent(filePath)
    return fileUrl
}

func prepareAudioPlayer(){
    do {
        player = try AVAudioPlayer(contentsOf: getFileUrl())
        player.volume = 1.0
        player.delegate = self
    }
    catch let err{
        print("player errr \(err)")
    }
}
     }

You are only setting the time stamp once while loading the view. Instead set the time stamp in your record function.

I don’t understand how that will help?

Maybe I misunderstood your question. You have a problem that it overwrites the first recording with the second one? If your filename is the same each time you do a recording, it would overwrite itself.

What I want to do is to be able to record two different audio tracks think track a and track b. Two separate buttons think button a and button B call function a and function b. Function a records track a and function b records track b.

This topic was automatically closed after 166 days. New replies are no longer allowed.