Swift录音机

时间:2018-03-28 17:11:43

标签: swift avaudioplayer audio-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")
        }

}

当我删除文件仍然显示在表视图中但我无法播放它。所以我想它是从目录中删除而不是从表视图中删除。所以我用过     myTableView.deleteRows(at:[indexPath],with:UITableViewRowAnimation.automatic)

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

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

以下是我的代码

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")
        }

}
}

}

1 个答案:

答案 0 :(得分:0)

[ 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
}