我正在尝试编写一段代码来录制 2 秒的音频,并在录制完成后自动播放。这段代码没有错误,但是好像根本没有录音,直接跳进if循环打印“录音成功...”,不播放任何东西。
@IBAction func buttonPressedDAF(_ sender: UIButton) {
print("starting DAF...")
let filename = getDirectory().appendingPathComponent("\(fileNameString)")
let settings = [AVFormatIDKey: Int(kAudioFormatAppleLossless),
AVEncoderAudioQualityKey: AVAudioQuality.max.rawValue,
AVEncoderBitRateKey: 320000,
AVNumberOfChannelsKey: 1,
AVSampleRateKey: 12000.0] as [String : Any]
do{
audioRecorder = try AVAudioRecorder(url: filename, settings: settings)
audioRecorder.delegate = self
if(audioRecorder.record(forDuration: 2 ))
{
print("recording succesfull...")
audioRecorder.stop()
audioRecorder = nil
playRecording()
}
}
catch {
print ("failed...")
}
我之前已经使用过 AV Audio,并且在实现基于开始、停止按钮的录音机时没有问题,但是在这里,record(forDurartion:) 函数似乎无法正常工作。
提前致谢
最佳答案
如果没有完成 block ,你可以使用我下面的代码来延迟调用停止记录代码:)
@IBAction func buttonPressedDAF(_ sender: UIButton) {
print("starting DAF...")
let filename = getDirectory().appendingPathComponent("\(fileNameString)")
let settings = [AVFormatIDKey: Int(kAudioFormatAppleLossless),
AVEncoderAudioQualityKey: AVAudioQuality.max.rawValue,
AVEncoderBitRateKey: 320000,
AVNumberOfChannelsKey: 1,
AVSampleRateKey: 12000.0] as [String : Any]
do{
audioRecorder = try AVAudioRecorder(url: filename, settings: settings)
audioRecorder.delegate = self
if(audioRecorder.record(forDuration: 2 ))
{
// .now() + number of seconds
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
print("recording succesfull...")
self.audioRecorder.stop()
self.audioRecorder = nil
self.playRecording()
}
}
}
catch {
print ("failed...")
}
关于ios - 如何使用 AV Audio 录制一段特定时间的音频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53466983/