APP重新启动后,AVAudioRecorder的初始录制始终为静音/无效

时间:2018-08-08 10:51:15

标签: ios swift swift3 avaudiosession avaudiorecorder

我为AVAudioRecorder提供了以下代码。该代码有效,除了启动/重新启动APP之后的初始记录始终为null / silent。有没有人遇到过类似的问题,或者您在我的代码中看到错误了?

import UIKit
import AVFoundation

class ViewController: UIViewController, AVAudioRecorderDelegate {
    var recordingSession:AVAudioSession!
    var audioRecorder:AVAudioRecorder!
    var player:AVAudioPlayer!
    var soundURL:URL!
    override func viewDidLoad() {
        super.viewDidLoad()
        recordingSession = AVAudioSession.sharedInstance()

        soundURL = getDirectory().appendingPathComponent("record.m4a")
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func Rcrd(_ sender: Any) {

        if audioRecorder == nil
        {

            let filename = getDirectory().appendingPathComponent("record.m4a")

            let settings = [AVFormatIDKey: Int(kAudioFormatMPEG4AAC), AVSampleRateKey: 1200, AVNumberOfChannelsKey: 1, AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue]

            //Start audio recording
            do
            {
                audioRecorder = try AVAudioRecorder(url: filename, settings: settings)
                audioRecorder.delegate = self
                audioRecorder.record()

                //buttonLabel.setImage(UIImage(named: "stopBtn.png"), for: .normal)
            }
            catch{
                displayAlert(title: "UPS!",message:NSLocalizedString("RcrdFl", comment: ""))
            }

        }
        else{
            //Stopping audio recording
            audioRecorder.stop()
            audioRecorder = nil

           let filename = getDirectory().appendingPathComponent("record.m4a")

            do {
                player = try AVAudioPlayer(contentsOf: filename)
                player.play()
            } catch let error as NSError {
                print(error.description)
            }



        }
    }

    @IBAction func Ply(_ sender: Any) {
        do {
            player = try AVAudioPlayer(contentsOf: soundURL)
            player.play()
        } catch let error as NSError {
            print(error.description)
        }
    }

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

    //Function that displats an alert
    func displayAlert(title:String,message:String)
    {
        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil ))
        present(alert, animated: true, completion: nil)
    }
}

如果您有另一个工作的avudiorecorder,请将其发送给我

0 个答案:

没有答案