单击时avaudioPlayer音频未打开(swift4)

时间:2019-01-14 23:02:40

标签: ios swift avfoundation avaudioplayer avaudiorecorder

AVaudioPlayer的声音文件未打开,因此,我录制的声音均未在表视图中播放。我可以保存到索引,并且可以在tableview上看到它。但是,当我单击tableview单元格时,我在日志文件中看到此错误消息。

2019-01-14 17:59:24.727900-0500 audioForAntoehr[6991:65804] [AXMediaCommon] Unable to look up screen scale

以下代码是我的源代码。我只是使用一个视图控制器。

import UIKit;import AVFoundation

class ViewController: UIViewController, AVAudioRecorderDelegate, UITableViewDataSource, UITableViewDelegate {
    var recordingSessioin: AVAudioSession!
    var audioRecorder: AVAudioRecorder!
    var aduioPlayer : AVAudioPlayer!

    @IBOutlet var mytableVie3w : UITableView!

    var numberOfRecords = 0
    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)
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let path = getD().appendingPathComponent("\(indexPath.row + 1).m4a")

        do {
            aduioPlayer = try AVAudioPlayer(contentsOf: path)
            aduioPlayer.play()
        }
        catch {

        }}
    @IBOutlet var buttonL:UIButton!
    @IBAction func record(_ sender: Any){
        if audioRecorder == nil {
            numberOfRecords += 1
            let fileName = getD().appendingPathComponent("\(numberOfRecords).m4a")
            let settings = [AVFormatIDKey: Int(kAudioFormatMPEG4AAC), AVSampleRateKey : 12000, AVNumberOfChannelsKey : 1, AVEncoderBitRateKey : AVAudioQuality.high.rawValue]


            do {
                audioRecorder = try AVAudioRecorder(url: fileName, settings: settings)
                audioRecorder.delegate = self
                audioRecorder.record()
                buttonL.setTitle("stop", for: .normal)

            }

                catch {
                    dsiaplery(title: "Ups", message: "it failed")
                }
        }
            else {
            audioRecorder.stop()
            audioRecorder = nil
                buttonL.setTitle("Stat", for: .normal)
             UserDefaults.standard.set(numberOfRecords, forKey: "myN")
            }



        }


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        recordingSessioin = AVAudioSession.sharedInstance()

        AVAudioSession.sharedInstance().requestRecordPermission { (hasPermission) in
            if hasPermission {
                print("accepted")
            }
        }
        if let number:Int = UserDefaults.standard.object(forKey: "myN") as? Int
        {
            numberOfRecords = number
        }
    }

    func getD() -> URL {
        let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        let documenterd = paths[0]
        return documenterd
    }

    func dsiaplery(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)


    }
}

1 个答案:

答案 0 :(得分:0)

编辑: 在这里更好的答案 How to play a sound using swift

当您需要在iOS中播放一些音频时,需要指定与播放器的共享会话。 需要将iOS环境(OS)通知已知的需求。

在调用audioPlayer.play()之前,需要将会话设置为当前的audioPlayer,当前的方法应如下所示。

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let path = getD().appendingPathComponent("\(indexPath.row + 1).m4a")
    do {
    // current class instance
         if (self.playSession == nil) {
                self.playSession = AVAudioSession.sharedInstance()
                try self.playSession.setCategory(AVAudioSessionCategoryPlayback, with: AVAudioSessionCategoryOptions.mixWithOthers)
         }
        aduioPlayer = try AVAudioPlayer(contentsOf: path)
        aduioPlayer.play()
    } catch {}

}

iOS Audio Session