我遇到了创建记录语音并播放结果的模块的问题。问题是,如果一个记录和播放它的工作,但如果一个记录,后来我得到之前创建的文件并尝试播放我得到:Error Domain=NSOSStatusErrorDomain Code=1685348671 "(null)"
103: OpenFromDataSource failed
78: Open failed
这是我使用的代码的简化版本:
var soundRecorder : AVAudioRecorder!
var SoundPlayer : AVAudioPlayer!
var recordingSession: AVAudioSession!
func getFileURL() -> URL {
let record = getDocumentsDirectory().appendingPathComponent(fileName)
return record
}
func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return paths[0]
}
override func viewDidLoad() {
super.viewDidLoad()
setupRecorder()
displaylinkRecording()
}
func setupRecorder(){
let recordSettings = [
AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
AVSampleRateKey: 44100,
AVNumberOfChannelsKey: 2,
AVEncoderAudioQualityKey: AVAudioQuality.max.rawValue
]
do {
try! AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord)
soundRecorder = try AVAudioRecorder(url: getFileURL(), settings: recordSettings)
soundRecorder.delegate = self
soundRecorder.isMeteringEnabled = true
soundRecorder.prepareToRecord()
} catch {
print("error recording")
}
}
我正在从其他ViewController更新文件名:
func UpdateNameFile() {
fileName = reg.idEvent + ".m4a"
setupRecorder()
}
相应的record
和play
函数:
@IBAction func Recording(_ sender: UIBarButtonItem) {
soundRecorder.record()
displaylinkRecording()
}
@IBAction func PlayButton(_ sender: UIBarButtonItem) {
preparePlayer()
SoundPlayer.play()
displaylinkPlaying()
}
func preparePlayer(){
do {
try! AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord)
SoundPlayer = try AudioPlayer(contentsOf: getFileURL() as URL)
SoundPlayer.delegate = self
SoundPlayer.isMeteringEnabled = true
SoundPlayer.prepareToPlay()
SoundPlayer.volume = 1.0
} catch {
print(error)
}
}
所以换句话说,如果我尝试录制和播放,可以工作,但如果我尝试播放一个我知道的文件在目录中并且之前已创建的文件,那么它不起作用。我不明白为什么......
有什么建议吗?