简体   繁体   中英

avaudioPlayer audio not opening when clicked (swift4)

Sound file from AVaudioPlayer is not opening, therefor none of the sound that I have recorded is playing on the tableview. I can save to the index and I see it on the tableview. But when I click on the tableview cell I see in the log file this error message.

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

The code below is my source code. I am just using one view controller.

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)


    }
}

Edit: A better answer over here How to play a sound using swift

When you need play some audio in iOS you need specify your shared session to player. iOS environment (OS) need be notifyed to known what want.

Before you call audioPlayer.play() you need set the session to current audioPlayer, your current method should look like this.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM