【发布时间】:2024-01-07 20:07:01
【问题描述】:
我正在使用 AVFoundation 来录制和播放语音。该应用程序在模拟器上运行良好。但是,在我的 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")
}
}
“注意: 当我在创建录制文件和播放文件时使用打印线作为路径时完全相同,但我不知道为什么它会引发错误“
【问题讨论】:
-
您是否确认在录制时委托方法被调用,并且您的录制首先完全成功?
-
是的,委托方法被调用,并且在我的 iPhone 中,当我按下记录并停止记录时,没有显示错误。但如果我想玩它,就会出现错误。 @Shripada
-
你能确保音频文件被创建了吗?
-
好吧,当我将 print(getFileURL()) 放入设置记录器和创建 soundReorder 之前,它显示以文件名结尾的相同路径。如何确保确实创建了音频文件? @Shripada
标签: swift swift2 avaudioplayer