iOS:AVAudioRecorder.prepareToRecord()失败,没有错误
问题描述:
prepareToRecord()
返回false,没有明显的原因。其他类似问题的解决方案都不适合我。以下是我所尝试的:iOS:AVAudioRecorder.prepareToRecord()失败,没有错误
- 在创建
AVAudioRecorder
之前立即开始记录会话(成功)。 - 输出目录存在并且是可写的。
- 这些
recordSettings
在我的代码的早期版本(现在丢失)中为我工作,但由于某种原因通常录制已停止。 - 我一直在使用
OpenEars
做语音识别,但是当我发现这个问题时,我从构建中删除了它。
版本信息:
- 的iOS 9.1
- 的XCode 7.1
- 雨燕2.1
这里是我的代码。模拟器和iPhone上的输出如下。
func setupRecorder(url : String) -> Promise<Void>? {
let (doneRecording, recorderAccept, _) = Promise<Void>.pendingPromise()
let session: AVAudioSession = AVAudioSession.sharedInstance()
if (session.respondsToSelector("requestRecordPermission:")) {
AVAudioSession.sharedInstance().requestRecordPermission({(granted: Bool)-> Void in
if granted {
print("record permission granted")
do {
try session.setCategory(AVAudioSessionCategoryPlayAndRecord)
try session.setActive(true)
self._setupRecorder(url, recorderAccept: recorderAccept)
} catch {
print(error)
}
} else{
print("record permission not granted")
}
})
}
return doneRecording
}
func _setupRecorder(url: String, recorderAccept:() ->()) {
print(url)
let recordSettings = [AVSampleRateKey : NSNumber(float: Float(44100.0)),
AVFormatIDKey : Int(kAudioFormatMPEG4AAC),
AVNumberOfChannelsKey : NSNumber(int: 1),
AVEncoderAudioQualityKey : NSNumber(int: Int32(AVAudioQuality.High.rawValue))];
do {
let soundRecorder = try AVAudioRecorder(URL: NSURL(fileURLWithPath: url), settings: recordSettings)
soundRecorder.delegate = self
if !soundRecorder.prepareToRecord() {
print("prerecord failed")
return
}
if !soundRecorder.record() {
print("record failed")
return
}
self.soundRecorder = soundRecorder
self.recorderAccept = recorderAccept
} catch let error as NSError {
print("AVAudioRecorder error: \(error.localizedDescription)")
}
}
iPhone输出:
record permission granted
file:///var/mobile/Containers/Data/Application/1DC339E6-555F-47AA-8D4F-4A8E1E847919/Library/Caches/iM3xWVKCGr.aac
prerecord failed
模拟器输出:
record permission granted
file:///Users/adrian/Library/Developer/CoreSimulator/Devices/5D035D65-60FA-413E-9CD7-C2C4277EC25F/data/Containers/Data/Application/6DF6374E-3BCF-4BD0-B826-FE1622F134B4/Library/Caches/1ey96W904T.aac
prerecord failed
缓存目录权限:
drwxr-xr-x 53 adrian admin 1802 Oct 29 14:12 /Users/adrian/Library/Developer/CoreSimulator/Devices/5D035D65-60FA-413E-9CD7-C2C4277EC25F/data/Containers/Data/Application/6DF6374E-3BCF-4BD0-B826-FE1622F134B4/Library/Caches/
我很想听听其他人有一个建议。
答
以下是我的代码中的错误:NSURL(fileURLWithPath: url)
。它应该是NSURL(string: url)!
- 我给它一个file://
的URL,就好像它是一个文件系统路径。
与此问题的其他问题一致prepareToRecord()
如果设置不正确或者在我的情况下打开输出文件时出现问题,则返回false。
先前在模拟器和设备上使用上述设置录制了录制内容。当我有机会时,我会从头开始构建一个新的录制应用程序。 – user2683747
想通了。谢谢,马特。 – user2683747