Swift 录音机

Swift Audio Recorder

您好,我正在制作录音机。我有几个问题 以下是我删除的音频文件片段。

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    let path = getDirectory().appendingPathComponent("Recording\(indexPath.row + 1).m4a")
    if editingStyle == .delete {
        do{

            try? FileManager.default.removeItem(at: path)
            myTableView.reloadData()
        } catch{
            displayAlert(title: "OOPS", message: "Delete failed")
        }

}

当我删除文件时,文件仍显示在 table 视图中,但我无法播放它。所以我猜它是从目录中删除的,而不是从 table 视图中删除的。所以我用 myTableView.deleteRows(位于:[indexPath],其中:UITableViewRowAnimation.automatic)

但它正在使应用程序崩溃...当我在网上搜索时,人们正在创建数组并从中删除音频。我应该创建数组还是可以删除 URL 本身

q2。在 table 视图中,音频文件名列为 1、2、3 等,但我希望名称为 Recording1、Recording2 等,给定文件的文件名是用 "Recording" 创建的在文档目录中但不在 table 视图中.. 如何给出正确的名称?

以下是我的代码

class ViewController: UIViewController, AVAudioRecorderDelegate, UITableViewDelegate, UITableViewDataSource{


var recordingSession: AVAudioSession!
var audioRecorder: AVAudioRecorder!
var audioPlayer: AVAudioPlayer!
var noOfRecords: Int = 0
@IBOutlet weak var recordButton: UIButton!

@IBOutlet weak var myTableView: UITableView!
@IBAction func recordPressed(_ sender: Any) {
    if audioRecorder == nil{

        noOfRecords += 1
        let fileName =   getDirectory().appendingPathComponent("Recording\(noOfRecords).m4a")
        print(fileName)
        let settings = [AVFormatIDKey: Int(kAudioFormatMPEG4AAC), AVSampleRateKey: 12000, AVNumberOfChannelsKey: 1, AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue]

        do{
            //record the audio
            audioRecorder = try AVAudioRecorder(url: fileName, settings: settings)
            audioRecorder.record()
            audioRecorder.delegate = self
            recordButton.setTitle("Stop Recording", for: .normal)

        }catch{
            displayAlert(title: "OOPS", message: "Recording failed")
        }
    } else {
            audioRecorder.stop()
            audioRecorder = nil
            recordButton.setTitle("Start Recording", for: .normal)
        //store the last no for naming
            UserDefaults.standard.set(noOfRecords, forKey: "myNumber")
        myTableView.reloadData()
    }

}
override func viewDidLoad() {
    super.viewDidLoad()

    //Ask permission for Mic
    recordingSession = AVAudioSession.sharedInstance()
    AVAudioSession.sharedInstance().requestRecordPermission { (hasPermission) in
        if hasPermission { print("Accepted")}

        //storing numbering logic
        if let number = UserDefaults.standard.object(forKey: "myNumber") as? Int
        { self.noOfRecords = number }

    }
}
//func to give path(URL) to store the recording
func getDirectory() -> URL {
    let path = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    let docDirectory = path[0]
    return docDirectory
}

//func to display 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 noOfRecords
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    cell.textLabel?.text = String(indexPath.row + 1)
    return cell
}

// listen to recorded audio
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let path = getDirectory().appendingPathComponent("Recording\(indexPath.row + 1).m4a")
    print(path)
    do{
    audioPlayer = try AVAudioPlayer(contentsOf: path)
    audioPlayer.play()
    } catch{
        displayAlert(title: "OOPS", message: "Playback failed")
    }
}
// to delete the recording

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    let path = getDirectory().appendingPathComponent("Recording\(indexPath.row + 1).m4a")
    if editingStyle == .delete {
        do{

            try? FileManager.default.removeItem(at: path)
            myTableView.reloadData()
        } catch{
            displayAlert(title: "OOPS", message: "Delete failed")
        }

}
}

}

[swift 4] 以下代码对我有用。使用 tableView.deleteRows

 func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    let path = getDirectory().appendingPathComponent("Recording\(indexPath.row + 1).m4a")
    if editingStyle == .delete {
        do{
            print("test", indexPath)
            try? FileManager.default.removeItem(at: path)
             noOfRecords -= 1
            tableView.deleteRows(at: [indexPath], with: .automatic)
            UserDefaults.standard.set(noOfRecords, forKey: "myNumber")
        } catch{
            displayAlert(title: "OOPS", message: "Delete failed")
        }
    }
}

对于第二个问题,使用文件夹中的文件名并显示如下:

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let path = getDirectory().appendingPathComponent("Recording\(indexPath.row + 1).m4a")
    let fileName = URL(fileURLWithPath: path.absoluteString).deletingPathExtension().lastPathComponent
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    cell.textLabel?.text = fileName
    return cell
}