我已经找到了一个用AVAudioEngine记录的示例代码&成功地输出了sampleRate 22050 aac格式的audioFile。
在我查看代码之后,有一个问题是我必须setCategory AVAudioSessionCategoryPlayAndRecord而不是AVAudioSessionCategoryRecord。
如何改进使用"AVAudioSessionCategoryRecord“而不使用"PlayAndRecord”的代码?
(在这种情况下,我应该使用"AVAudioSessionCategoryRecord",对吗?)
如果我setCategory到AVAudioSessionCategoryRecord,就会得到一个错误:
IsFormatSampleRateAndChannelCountValid(outputHWFormat):AVAudioEngineGraph.mm:1070: required条件为false: AVAudioEngineGraph.mm:1070 终止应用程序的原因是:“必需条件为假: IsFormatSampleRateAndChannelCountValid(outputHWFormat)‘”
有一个关于在AVAudioSessionCategoryRecord中使用麦克风的例子,在我看来,我们只能用inputNode录制。https://developer.apple.com/library/prerelease/content/samplecode/SpeakToMe/Introduction/Intro.html
下面的代码现在可以工作了。
import UIKit
import AVFoundation
class ViewController: UIViewController {
let audioEngine = AVAudioEngine()
lazy var inputNode : AVAudioInputNode = {
return self.audioEngine.inputNode!
}()
let sampleRate = Double(22050)
lazy var outputFormat : AVAudioFormat = {
return AVAudioFormat(commonFormat: self.inputNode.outputFormatForBus(0).commonFormat,
sampleRate: self.sampleRate,
channels: AVAudioChannelCount(1),
interleaved: false)
}()
let converterNode = AVAudioMixerNode()
lazy var aacFileURL : NSURL = {
let dirPath = NSURL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)
let filePath = dirPath.URLByAppendingPathComponent("rec.aac")
return filePath
}()
lazy var outputAACFile : AVAudioFile = {
var settings = self.outputFormat.settings
settings[AVFormatIDKey] = NSNumber(unsignedInt: kAudioFormatMPEG4AAC)
return try! AVAudioFile(forWriting: self.aacFileURL,
settings:settings)
}()
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
let audioSession = AVAudioSession.sharedInstance()
try! audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord)
try! audioSession.setActive(true)
self.audioEngine.attachNode(converterNode)
self.audioEngine.connect(inputNode,
to: converterNode,
format: inputNode.outputFormatForBus(0))
self.audioEngine.connect(converterNode,
to: self.audioEngine.mainMixerNode,
format: outputFormat)
converterNode.volume = 0
converterNode.installTapOnBus(0, bufferSize: 1024, format: converterNode.outputFormatForBus(0)) { (buffer, when) in
try! self.outputAACFile.writeFromBuffer(buffer)
}
try! self.audioEngine.start()
}
}
相关链接
发布于 2017-01-18 14:47:37
AVAudioMixerNode
无法在非压缩格式和压缩格式之间进行转换。为此,您需要AVAudioConverter
。
https://stackoverflow.com/questions/38663496
复制相似问题