Skip to content

Instantly share code, notes, and snippets.

@dreamwieber
Created November 26, 2014 18:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dreamwieber/455c2f2073139bd591f6 to your computer and use it in GitHub Desktop.
Save dreamwieber/455c2f2073139bd591f6 to your computer and use it in GitHub Desktop.
AVAudioFile
import AVFoundation
private let _singletonInstance = AudioController()
class AudioController {
class var sharedInstance: AudioController {
return _singletonInstance
}
let audioEngine: AVAudioEngine = AVAudioEngine()
let input: AVAudioInputNode
let output: AVAudioOutputNode
let inputFormat: AVAudioFormat
var isMonitoring: Bool
var isRecording: Bool
var audioFile: AVAudioFile!
init() {
input = audioEngine.inputNode
output = audioEngine.outputNode
inputFormat = input.inputFormatForBus(0)
isMonitoring = false
isRecording = false
}
func monitorInput() -> NSError? {
if (audioEngine.running) {
audioEngine.pause()
}
audioEngine.connect(input, to: output, format: inputFormat)
var error: NSError?
audioEngine.startAndReturnError(&error)
if error == nil {
isMonitoring = true
} else {
isMonitoring = false
}
return error
}
func stopMonitoringInput() -> NSError? {
if (audioEngine.running) {
audioEngine.pause()
}
audioEngine.disconnectNodeOutput(input)
var error: NSError?
audioEngine.startAndReturnError(&error)
if error == nil {
isMonitoring = false
} else {
isMonitoring = true
}
return error
}
func startRecording() {
let url = fileUtilDocumentsDirectoryURLWithFilename("test.aiff")
let settings =
[AVFormatIDKey: kAudioFormatLinearPCM,
AVSampleRateKey: inputFormat.sampleRate,
AVNumberOfChannelsKey: 2,
AVLinearPCMBitDepthKey : 32,
AVLinearPCMIsBigEndianKey : false,
AVLinearPCMIsFloatKey : true,
AVLinearPCMIsNonInterleaved : false];
var error : NSError?
self.audioFile = AVAudioFile(forWriting: url, settings: settings, commonFormat: AVAudioCommonFormat.PCMFormatFloat32, interleaved: false, error: &error)
if (error != nil) {
println(String(format: "error creating audio file %@", error!))
return
}
println("recording to file: " + url!.absoluteString!)
input.installTapOnBus(0, bufferSize: 4096, format: nil) { (buffer, when) -> Void in
var writeError: NSError?
self.audioFile.writeFromBuffer(buffer, error: &writeError)
}
isRecording = true
}
func stopRecording() {
input.removeTapOnBus(0)
isRecording = false
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment