我正在使用AVFoundation录制和播放声音。 该应用程序在Simulator上运行良好。 但是,在我的iPhone 5S(运行IOS 9)中,它记录了语音问候,但没有播放语音。 播放录制的声音(操作无法完成。(OSStatus错误-39。)“))和下一行时,我总是会出现错误(严重错误:在展开Optional值时意外发现nil)。
然后,我在以下代码行中发现了错误:
self._SoundPlayer = try AVAudioPlayer(contentsOfURL: getFileURL())
“它总是抛出错误”
这是getFileURL()代码:
func getCacheDirectory() -> String {
let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
return paths[0]
}
func getFileURL() -> NSURL{
let path = (getCacheDirectory() as NSString).stringByAppendingPathComponent(fileName)
let filePath = NSURL(fileURLWithPath: path)
return filePath
}
这是设置记录文件代码:
func setupRecorder(){
let recordSettings = [AVSampleRateKey : NSNumber(float: Float(44100.0)),
AVFormatIDKey : NSNumber(int: Int32(kAudioFormatMPEG4AAC)),
AVNumberOfChannelsKey : NSNumber(int: 2),
AVEncoderAudioQualityKey : NSNumber(int: Int32(AVAudioQuality.High.rawValue)),
AVEncoderBitRateKey : NSNumber(int: Int32(320000))]
do {
_soundRecorder = try AVAudioRecorder(URL: getFileURL(), settings: recordSettings)
_soundRecorder.delegate=self
_soundRecorder.prepareToRecord()
print(getFileURL())
}
catch {
print("error")
}
}
“注意:当我在创建记录的文件和播放文件时使用打印线作为路径时,完全相同,但是我不知道为什么它会引发错误”
我删除了getCacheDirectory()和getFileURL()方法,而是将这段代码添加了下来,并且效果很好
let fileManager = NSFileManager.defaultManager().URLsForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomains: NSSearchPathDomainMask.UserDomainMask).first
let soundURL = fileManager!.URLByAppendingPathComponent("audio.m4a")