我想使用AVAudioEngine录制音频文件。所以它将从麦克风到输出文件。稍后我会添加一些效果。但就目前而言,我只想让它发挥作用。
任何人都可以向我提供步骤或示例代码,以便我可以开始吗?
答案 0 :(得分:6)
这是我的简单解决方案。输出文件将在文档目录中。请注意,为简洁起见,我删除了错误处理。
var engine = AVAudioEngine()
var file: AVAudioFile?
var player = AVAudioPlayerNode() // if you need play record later
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
file = AVAudioFile(forWriting: URLFor("my_file.caf")!, settings: engine.inputNode.inputFormatForBus(0).settings, error: nil)
engine.attachNode(player)
engine.connect(player, to: engine.mainMixerNode, format: engine.mainMixerNode.outputFormatForBus(0)) //configure graph
engine.startAndReturnError(nil)
}
@IBAction func record(sender: AnyObject) {
engine.inputNode.installTapOnBus(0, bufferSize: 1024, format: engine.mainMixerNode.outputFormatForBus(0)) { (buffer, time) -> Void in
self.file?.writeFromBuffer(buffer, error: nil)
return
}
}
@IBAction func stop(sender: AnyObject) {
engine.inputNode.removeTapOnBus(0)
}
func URLFor(filename: String) -> NSURL? {
if let dirs : [String] = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) as? [String] {
let dir = dirs[0] //documents directory
let path = dir.stringByAppendingPathComponent(filename)
return NSURL(fileURLWithPath: path)
}
return nil
}