Я работаю над проектом, в котором я записываю голос пользователя и сохраняю его в ячейке UITableView, где они могут нажать на него и воспроизвести аудио. По какой-то причине звук не воспроизводится при нажатии ... я неправильно сохраняю файл или получаю его неправильно? Iv'e тоже пытался использовать разные методы, но они, похоже, не работали ... И как мне сохранить файл как имя, данное пользователем? Заранее спасибо за помощь!
//
// ViewController.swift
// Voice Notes
//
// Created by Manav Chordia on 25/01/20.
// Copyright © 2020 Manav Chordia. All rights reserved.
//
import UIKit
import AVFoundation
class ViewController: UIViewController, AVAudioRecorderDelegate, UITableViewDelegate, UITableViewDataSource, AVAudioPlayerDelegate {
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
{
startRecording(sucsess: true)
/*
let settings = [AVFormatIDKey: Int(kAudioFormatMPEG4AAC), AVSampleRateKey: 12000, AVNumberOfChannelsKey: 1, AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue]
//Start Recording
do
{
audioRecorder = try AVAudioRecorder(url: filename, settings: settings)
audioRecorder.delegate = self
audioRecorder.record()
buttonLabel.setTitle("Stop Recording", for: .normal)
}
catch
{
displayAlert(title: "OoPs", message: "Recording FAILED")
}*/
}else
{
finishRecording(success: true)
/*
//Stop Recording
audioRecorder.stop()
audioRecorder = nil
buttonLabel.setTitle("Record!", for: .normal)
*/
}
}
func startRecording(sucsess: Bool) {
numberOfRecords += 1
let filename = getDirectory().appendingPathComponent("\(numberOfRecords).m4a")
let settings = [
AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
AVSampleRateKey: 12000,
AVNumberOfChannelsKey: 1,
AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
]
do {
audioRecorder = try AVAudioRecorder(url: filename, settings: settings)
audioRecorder.delegate = self
audioRecorder.record()
buttonLabel.setTitle("Tap to Stop", for: .normal)
// playButton.isEnabled = false
} catch {
finishRecording(success: false)
}
}
func finishRecording(success: Bool) {
audioRecorder.stop()
audioRecorder = nil
if success {
buttonLabel.setTitle("Tap to Record New", for: .normal)
UserDefaults.standard.set(numberOfRecords, forKey: "myNumber")
myTableView.reloadData()
} else {
buttonLabel.setTitle("Tap to Record", for: .normal)
// recording failed :(
}
//playButton.isEnabled = true
buttonLabel.isEnabled = true
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
//Setting up sessions
recordingSession = AVAudioSession.sharedInstance()
if let number:Int = UserDefaults.standard.object(forKey: "myNumber") as? Int
{
numberOfRecords = number
}
AVAudioSession.sharedInstance().requestRecordPermission { (hasPremission) in
if hasPremission
{
print ("ACCEPTED")
}
}
}
//Function that gets path to directory.
func getDirectory() -> URL
{
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documetDirectory = paths[0]
return documetDirectory
}
func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
if !flag {
finishRecording(success: false)
}
}
func audioRecorderEncodeErrorDidOccur(_ recorder: AVAudioRecorder, error: Error?) {
print("Error while recording audio \(error!.localizedDescription)")
}
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
buttonLabel.isEnabled = true
//playButton.setTitle("Play", for: .normal)
}
func audioPlayerDecodeErrorDidOccur(_ player: AVAudioPlayer, error: Error?) {
print("Error while playing audio \(error!.localizedDescription)")
}
// function that displays 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)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let path = getDirectory().appendingPathComponent("\(indexPath.row).m4a")
/*if (sender.titleLabel?.text == "Play"){
recordButton.isEnabled = false
sender.setTitle("Stop", for: .normal)
preparePlayer()
audioPlayer.play()
} else {
audioPlayer.stop()
sender.setTitle("Play", for: .normal)
}*/
do
{
audioPlayer = try AVAudioPlayer(contentsOf: path)
audioPlayer.delegate = self
audioPlayer.volume = 1.0
audioPlayer.prepareToPlay()
audioPlayer.play()
}
catch
{
print(error)
}
}
/*
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
var cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
if editingStyle == UITableViewCell.EditingStyle.delete
{
tableView.remove(at: 0)
let indexPath = IndexPath(item: 0, section: 0)
tableView.deleteRows(at: [indexPath], with: .fade)
tableView.reloadData()
}
}*/
}
Я получаю ошибку "ERROR DID NOT PLAY", которую я дал в секции catch. как мне преодолеть эту ошибку?
также извините за столько комментариев?