在Swift中创建录音

时间:2015-11-22 04:27:06

标签: swift audio avfoundation avaudiorecorder recording

我开始通过创建一个允许用户录制语音备忘录的应用程序来自学Swift。关于这个主题的许多先前的问题似乎使用了过时的Swift版本,所以我想我会向社区寻求帮助。

问题似乎在于我的playAudio()函数或我设置录制URL(或两者)的viewDidLoad()函数。如果我能提供更多信息,请告诉我。

@IBAction func playAudio(sender: AnyObject) throws {

    if audioRecorder?.recording == false {

        stopButton.enabled = true
        recordButton.enabled = false
            let path = NSBundle.mainBundle().pathForResource("audioFile", ofType: "m4a")
            let fileURL = try NSURL(fileURLWithPath: path!)
            audioPlayer = try AVAudioPlayer(contentsOfURL: fileURL, fileTypeHint: nil)
            audioPlayer.prepareToPlay()
            audioPlayer.delegate = self
            print("here you go!")
    }
}

覆盖func viewDidLoad(){

    super.viewDidLoad()

    playButton.enabled = false
    stopButton.enabled = false

    do {
        let dirPaths =
            NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)

        let baseURL = NSURL(string: dirPaths[0])
        let soundFileURL = NSURL(string:"sound.caf", relativeToURL: baseURL)
        let absoluteURL = soundFileURL!.absoluteURL
        let recordSettings = [AVEncoderAudioQualityKey: AVAudioQuality.Min.rawValue, AVEncoderBitRateKey: 16, AVNumberOfChannelsKey: 2, AVSampleRateKey: 44100.0]
        var error: NSError?

        let audioSession = AVAudioSession.sharedInstance()
        try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord, withOptions: [])

        if let err = error {
            print("audioSession error: \(err.localizedDescription)")
        }

        try audioRecorder = AVAudioRecorder(URL: absoluteURL, settings: recordSettings as! [NSObject : AnyObject] as! [String: AnyObject])
        print(audioRecorder!.url)
        if let err = error {
            print("audioSession error: \(err.localizedDescription)")
        } else {
            audioRecorder?.prepareToRecord()
        }

    } catch {
        print("catching error!")
    }

0 个答案:

没有答案