我希望在OSX上捕获音频。我让IOS与AVAudioSession一起工作,但是由于OSX不支持它,所以我很难在OSX上找到一个简单的示例来将音频记录到文件中以供后续播放。
我在stackoverflow上发现的所有示例都是IOS,或者在Swift中不是。
这里的任何帮助将不胜感激。链接到基于OSX Swift的简单音频捕获示例代码会很棒。
感谢汤姆
答案 0 :(得分:0)
AVAudioSession
用于管理iOS音频限制。这些约束在macOS上不存在,因此您不需要AVAudioSession
。哇!
您可以使用AVAudioEngine
和AVAudioFile
将音频捕获到文件中:
import Cocoa
import AVFoundation
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet weak var window: NSWindow!
let audioEngine = AVAudioEngine()
var outputFile: AVAudioFile? = nil
func applicationDidFinishLaunching(_ aNotification: Notification) {
// If sandboxed, don't forget to turn on Microphone in Capabilities > App Sandbox
let input = audioEngine.inputNode
let bus = 0
let inputFormat = input.inputFormat(forBus: bus)
let outputURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("out.caf")
print("writing to \(outputURL)")
outputFile = try! AVAudioFile(forWriting: outputURL, settings: inputFormat.settings, commonFormat: inputFormat.commonFormat, interleaved: inputFormat.isInterleaved)
input.installTap(onBus: bus, bufferSize: 512, format: inputFormat) { (buffer, time) in
try! self.outputFile?.write(from: buffer)
}
try! audioEngine.start()
DispatchQueue.main.asyncAfter(deadline: .now()+5) {
print("Finish")
self.audioEngine.stop()
self.outputFile = nil
}
}
}
答案 1 :(得分:0)
Audio Queue API可以在iOS和macOS(OSX)上录制。因此,寻找一个音频队列示例;在github上似乎有几个。