Мой телефон подключен к микрофону и наушникам.Пользователь должен иметь возможность слышать через наушники то, что записывается одновременно, через микрофон.Как бы я это сделал?Приложение для записи просто, как видно из следующего кода.Я не уверен, как на самом деле воспроизвести звук, прежде чем он будет записан.
import UIKit
import AVFoundation
class ViewController: UIViewController, AVAudioRecorderDelegate, UITableViewDelegate, UITableViewDataSource{
var recordingSession : AVAudioSession!
var audioRecorder : AVAudioRecorder!
var numberOfRecords:Int = 0
var audioPlayer:AVAudioPlayer!
@IBOutlet weak var myTableView: UITableView!
@IBOutlet weak var buttonLabel: UIButton!
@IBAction func record(_ sender: Any) {
//Check if we have an active recorder
if audioRecorder == nil {//we dont have an active recorder
numberOfRecords += 1
let fileName = getDirectory().appendingPathComponent("\(numberOfRecords).m4a")
let settings = [AVFormatIDKey: Int(kAudioFormatMPEG4AAC), AVSampleRateKey: 12000, AVNumberOfChannelsKey: 1, AVEncoderAudioQualityKey:AVAudioQuality.high.rawValue]
//start audio recording
do{
audioRecorder = try AVAudioRecorder(url: fileName, settings: settings)
audioRecorder.delegate = self
audioRecorder.record()
buttonLabel.setTitle("Stop Recording", for: .normal)
}catch{
displayAlert(title: "Error!", message: "Recording Failed")
}
}
else{
//Stopping audio recording
audioRecorder.stop()
audioRecorder = nil
UserDefaults.standard.set(numberOfRecords, forKey: "myRecorNumber")
myTableView.reloadData()//refresh the table to add new ones
buttonLabel.setTitle("Start Recoring", for: .normal)
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
//setting up session
recordingSession = AVAudioSession.sharedInstance()
if let number:Int = UserDefaults.standard.object(forKey: "myRecorNumber") as? Int{
numberOfRecords = number //when app launched, if there are something in the user defaults, continue from there and do not evrride the number of records
}
AVAudioSession.sharedInstance().requestRecordPermission { (hasPermission) in
if hasPermission{
print("Accepted")
}
}
}
//FUnction that gets path to directory
func getDirectory() -> URL
{
let path = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentDirectory = path[0]
return documentDirectory
}
//Function that displays an alert
func displayAlert(title:String, message:String){
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "dismiss", style: .default, handler: nil))
present(alert, animated: true, completion: nil)
}
//Setting up table view
func tableView(_ tableView: UITableView, numberOfRowsInSection section:Int) -> Int {
return numberOfRecords
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = String(indexPath.row + 1) //naming the cell with aoudio recording
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let path = getDirectory().appendingPathComponent("\(indexPath.row + 1).m4a")
do{
audioPlayer = try AVAudioPlayer(contentsOf: path)
audioPlayer.play()
}catch{
}
}
}