简体   繁体   中英

AVAudioRecorder.record() always returns “false” in iOS 8

I'm trying to create a practice app using AVAudioRecorder that, upon pressing a button, records 1 second of audio through the iPhone's mic to a file called "Test.wav" and plays it back. However, both the record() and recordForDuration() methods both seem to fail every time I try to execute them. I've already tried setting up an AVAudioSession and making it active, but nothing seems to work. Any help would be greatly appreciated.

import UIKit

import AVFoundation

class ViewController: UIViewController, AVAudioRecorderDelegate {

@IBOutlet var recordAndPlayButton: UIButton!

let settings = [
    AVFormatIDKey: kAudioFormatLinearPCM,
    AVSampleRateKey: 192000.0,
    AVNumberOfChannelsKey: 1,
    AVLinearPCMBitDepthKey: 16,
    AVLinearPCMIsBigEndianKey: false,
    AVLinearPCMIsFloatKey: false,
    AVLinearPCMIsNonInterleaved: false
]

var audioSession = AVAudioSession.sharedInstance()
var recorder : AVAudioRecorder!

override func viewDidLoad() {
    audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord, error: nil)
    audioSession.setActive(true, error: nil)

    recorder = AVAudioRecorder(URL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Test", ofType: "wav")!), settings: settings, error: nil)
    recorder.delegate = self
    super.viewDidLoad()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

@IBAction func recordSoundAndPlay() {
    recorder.prepareToRecord()
    println(recorder.recordForDuration(1.0))

    var testSound = SystemSoundID()
    AudioServicesCreateSystemSoundID(NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Test", ofType: "wav")!), &testSound)
    AudioServicesPlaySystemSound(testSound)
}

}

I had this issue too - turns out it's not actually to do with AVAudioRecorder but actually the way user directories are structured in iOS8. See this question and answer for more info.

Anyway, I fixed it by changing the way the file was accessed to something more like this:

let DOCUMENTS_FOLDER: NSString! = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).first as NSString

@IBAction func recordSoundAndPlay() {
    recorder.prepareToRecord()
    println(recorder.recordForDuration(1.0))

    var testSound = SystemSoundID()
    AudioServicesCreateSystemSoundID(NSURL(fileURLWithPath: "\(DOCUMENTS_FOLDER)/Test.wav")), &testSound)
    AudioServicesPlaySystemSound(testSound)
}

Let me know how it goes!

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